Sử dụng dot notation truy cập nhiều cấp lồng nhau
MongoDB cho phép truy vấn trường ở độ sâu bất kỳ bằng cách nối tên trường với dấu chấm.
Dữ liệu 3 cấp lồng nhau
> db.demo350.insertOne({
id: 101,
Name: "Chris",
details: [{
_id: 1,
ClientNumber: "10001",
ClientDetails: [
{ Name: "David", Age: 29 },
{ Name: "Bob", Age: 31 }
]
}]
});
> db.demo350.insertOne({
id: 102,
Name: "David",
details: [{
_id: 2,
ClientNumber: "10002",
ClientDetails: [
{ Name: "Carol", Age: 42 },
{ Name: "John", Age: 37 }
]
}]
});
Tìm document có ClientDetails.Name = "John"
> db.demo350.find({ "details.ClientDetails.Name": "John" });
Kết quả
{
"_id": ObjectId("..."),
"id": 102,
"Name": "David",
"details": [{
"_id": 2,
"ClientNumber": "10002",
"ClientDetails": [
{ "Name": "Carol", "Age": 42 },
{ "Name": "John", "Age": 37 }
]
}]
}
Lưu ý: Trả về toàn bộ document. Để lấy chỉ phần tử khớp, dùng aggregation với $filter hoặc $elemMatch projection.