특정 요소를 가져오려면 forEach()로 반복합니다. 문서로 컬렉션을 만들자 −
> db.demo742.insertOne({ "userDetails": [ { "userName":"Robert", "CountryName":"UK" }, { "userName":"David", "CountryName":"AUS" } ]} );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ead790b57bb72a10bcf0677")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo742.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5ead790b57bb72a10bcf0677"),
"userDetails" : [
{
"userName" : "Robert",
"CountryName" : "UK"
},
{
"userName" : "David",
"CountryName" : "AUS"
}
]
} 다음은 배열에서 요소를 가져오는 쿼리입니다 -
> var ListOfCountryName= {};
> db.demo742.find({}).forEach(function(doc) {
... doc.userDetails.forEach(function (d){
... ListOfCountryName[d.CountryName] =d.CountryName;
... });
... }
... )
> printjson(ListOfCountryName); 이것은 다음과 같은 출력을 생성합니다 -
{ "UK" : "UK", "AUS" : "AUS" }