여러 하위 문서에서 필드를 가져오려면 $unwind와 함께 MongoDB 집계를 사용합니다. 문서로 컬렉션을 만들자 −
> db.demo671.insertOne(
... {
...
... "details" : [
... {
... "id" : "1"
... },
... {
... CountryName:"US",
... "details1" : [
... {
... "id" : "1"
... },
... {
... "id" : "2"
... }
... ]
... },
... {
... CountryName:"UK",
... "details1" : [
... {
... "id" : "2"
... },
... {
... "id" : "1"
... }
... ]
... },
... {
... CountryName:"AUS",
... "details1" : [
... {
... "id" : "1"
... }
... ]
... }
... ]
... }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3e5d004263e90dac943e0")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo671.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] } 다음은 MongoDB의 조건과 일치하는 여러 하위 문서에서 필드를 가져오는 쿼리입니다. -
> db.demo671.aggregate([
...
... {$unwind: '$details'},
...
... {$match: {'details.details1.id': '1'}},
...
... {$project: {_id: 0, Country: '$details.CountryName'}}
... ]).pretty() 이것은 다음과 같은 출력을 생성합니다 -
{ "Country" : "US" }
{ "Country" : "UK" }
{ "Country" : "AUS" }