Sử dụng toán tử $elemMatch lồng nhau để trích xuất phần tử sâu bên trong mảng lồng nhau. Tạo collection:
> 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 }
Hiển thị document:
> db.particularElementDemo.find().pretty();
Kết quả (cấu trúc lồng nhau 3 cấp).
Truy vấn trích xuất phần tử có Name = "Robert" trong mảng lồng nhau:
> db.particularElementDemo.find(
{
'UserDetails': {
$elemMatch: {
'UserOtherDetails': {
$elemMatch: {
'UserFriendName': { $elemMatch: { "Name": "Robert" } }
}
}
}
}
},
{ "UserDetails.UserOtherDetails.UserFriendName.Name": 1 }
);
Kết quả (chỉ trả về đường dẫn đến phần tử khớp):
{
"_id": 100,
"UserDetails": [
{
"UserOtherDetails": [
{ "UserFriendName": [ { "Name": "Chris" } ] },
{ "UserFriendName": [ { "Name": "Robert" } ] }
]
}
]
}