Để truy cập đối tượng lồng nhau, sử dụng dot notation (ký hiệu chấm) trong truy vấn.
Ví dụ: Collection nestedObjectDemo với cấu trúc lồng sâu:
> db.nestedObjectDemo.insertOne({
"Student": {
"StudentDetails": {
"StudentPersonalDetails": {
"StudentName": ["John"],
"StudentCountryName": ["US"],
"StudentCoreSubject": ["C", "Java"],
"StudentProject": ["Online Book Store", "Pig Dice Game"]
}
}
}
});
Xem dữ liệu:
> db.nestedObjectDemo.find().pretty();
Truy vấn tìm StudentName = "John" bằng dot notation:
> db.nestedObjectDemo.find({
"Student.StudentDetails.StudentPersonalDetails.StudentName": "John"
}).pretty();
Kết quả trả về toàn bộ tài liệu khớp.
Lưu ý:
- Dot notation hoạt động cả cho truy vấn (query) và projection.
- Nếu tên trường chứa dấu chấm hoặc ký tự đặc biệt, cần dùng ngoặc vuông:
{"field.name": value}. - Với mảng, dot notation khớp với bất kỳ phần tử nào trong mảng.