หากต้องการค้นหาระเบียน MongoDB ที่มีความลึก 2 ระดับ ให้วนรอบ MongoDB $where ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
... "StudentName" : "Chris",
... "StudentAge" : 23
... },
... "SecondPosition" : {
... "StudentName" : "David",
... "StudentAge" : 20
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e804e2fb0f3fa88e2279069")
}
> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
... "StudentName" : "Carol",
... "StudentAge" : 21
... },
... "SecondPosition" : {
... "StudentName" : "John",
... "StudentAge" : 22
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e804fb0b0f3fa88e227906a")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo468.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e804e2fb0f3fa88e2279069"), "FirstPosition" : { "StudentName" : "Chris",
"StudentAge" : 23 }, "SecondPosition" : { "StudentName" : "David", "StudentAge" : 20 } }
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } } ต่อไปนี้เป็นแบบสอบถามเพื่อค้นหาระเบียน MongoDB ที่มีความลึกสองระดับ -
> db.demo468.find({
... $where: function() {
... for (var i in this) {
... if (this[i]["StudentName"] == "John") {
... return true;
... }
... }
... return false;
... }
... }) สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } }