MongoDB에서 특정 요소를 추출하려면 $elemMatch 연산자를 사용할 수 있습니다. 먼저 문서로 컬렉션을 만들어 보겠습니다. −
> db.particularElementDemo.insertOne(
{
"GroupId" :"Group-1",
"UserDetails" : [
{
"UserName" : "John",
"UserOtherDetails" : [
{
"UserEmailId" : "John123@gmail.com",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "John22@hotmail.com",
"UserFriendName" : [
{
"Name" : "Robert"
}
]
}
]
}
]
}
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.particularElementDemo.find().pretty();
{
"_id" : 100,
"GroupId" : "Group-1",
"UserDetails" : [
{
"UserName" : "John",
"UserOtherDetails" : [
{
"UserEmailId" : "John123@gmail.com",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "John22@hotmail.com",
"UserFriendName" : [
{
"Name" : "Robert"
}
]
}
]
}
]
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.particularElementDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : 100,
"GroupId" : "Group-1",
"UserDetails" : [
{
"UserName" : "John",
"UserOtherDetails" : [
{
"UserEmailId" : "John123@gmail.com",
"UserFriendName" : [
{
"Name" : "Chris"
}
]
},
{
"UserEmailId" : "John22@hotmail.com",
"UserFriendName" : [
{
"Name" : "Robert"
}
]
}
]
}
]
} 다음은 중첩 배열에서 MongoDB의 특정 요소를 추출하는 쿼리입니다 -
> db.particularElementDemo.find(
{
'UserDetails':{
$elemMatch:{
'UserOtherDetails':{
$elemMatch:{
'UserFriendName':{ $elemMatch: {"Name" : "Robert" } }
}
}
}
}
},{"UserDetails.UserOtherDetails.UserFriendName.Name":1}
); 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : 100, "UserDetails" : [ { "UserOtherDetails" : [ { "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }