Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

ค้นหาค่าในออบเจ็กต์ที่มี Key เป็นตัวเลขด้วย $where ใน MongoDB


สร้างคอลเลกชันตัวอย่าง

เอกสารมีฟิลด์ 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" } }