Để truy cập phần tử bên trong mảng JSON, sử dụng ký pháp dấu chấm (dot notation) kết hợp với chỉ số mảng hoặc tên trường.
Tạo collection với cấu trúc lồng: CountryName, info.id, info.details[].otherDetails (Marks, Age):
> db.demo687.insert({CountryName:'US',
... info:
... {
... id:101,
... details:
... [
... {
... Name:'Chris',
... SubjectName:'MongoDB',
... otherDetails:{
... "Marks":58,
... Age:23
... }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
> db.demo687.insert({CountryName:'UK',
... info:
... {
... id:102,
... details:
... [
... {
... Name:'David',
... SubjectName:'MySQL',
... otherDetails:{
... "Marks":78,
... Age:21
... }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
Hiển thị tất cả:
> db.demo687.find();
Truy vấn tìm tài liệu có info.details.otherDetails.Marks = 58:
> db.demo687.find({"info.details.otherDetails.Marks":58});
Kết quả (tài liệu US, Chris, Marks 58):
{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }