สร้างคอลเลกชันตัวอย่าง
เอกสารมีฟิลด์ details เป็นออบเจ็กต์ที่ Key เป็นสตริงตัวเลข:
> db.demo268.insertOne(
{
"details": {
"101": "John",
"1001": "Bob"
}
}
);
{ "acknowledged": true, "insertedId": ObjectId("5e4816141627c0c63e7dbaaf") }
แสดงข้อมูล
> db.demo268.find();
{ "_id": ObjectId("5e4816141627c0c63e7dbaaf"), "details": { "101": "John", "1001": "Bob" } }
ค้นหาด้วย $where และ JavaScript Function
วนลูปตรวจสอบทุก key ในออบเจ็กต์ details:
> db.demo268.find({ $where:
function() {
for (var k in this.details) {
if (this.details[k] == "Bob") {
return true;
}
}
}
})
ผลลัพธ์
{ "_id": ObjectId("5e4816141627c0c63e7dbaaf"), "details": { "101": "John", "1001": "Bob" } }