Để tìm giá trị trong trường lồng nhau, sử dụng dấu chấm (.) hoặc dấu gạch dưới kép (__) trong truy vấn find().
Tạo collection với trường lồng nhau __StudentName:
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Smith"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f39125ddae1f53b621f0") }
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Doe"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f39e25ddae1f53b621f1") }
> db.nestedDemo.insertOne({"Information":{"__StudentName":"Chris Brown"}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f3a625ddae1f53b621f2") }
Hiển thị dữ liệu:
> db.nestedDemo.find().pretty();
{ "_id" : ObjectId("5e06f39125ddae1f53b621f0"), "Information" : { "__StudentName" : "John Smith" } }
{ "_id" : ObjectId("5e06f39e25ddae1f53b621f1"), "Information" : { "__StudentName" : "John Doe" } }
{ "_id" : ObjectId("5e06f3a625ddae1f53b621f2"), "Information" : { "__StudentName" : "Chris Brown" } }
Truy vấn tìm tài liệu có Information.__StudentName = "John Doe":
> db.nestedDemo.find({"Information.__StudentName":"John Doe"});
Kết quả khớp chính xác một tài liệu:
{ "_id" : ObjectId("5e06f39e25ddae1f53b621f1"), "Information" : { "__StudentName" : "John Doe" } }