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

ค้นหาเอกสาร MongoDB ที่อาร์เรย์ไม่มีค่าเฉพาะในฟิลด์ย่อย

สำหรับกรณีที่ต้องการค้นหาเอกสารที่อาร์เรย์มีองค์ประกอบที่ไม่มีฟิลด์เฉพาะ ให้ใช้ $elemMatch ตัวดำเนินการนี้จะจับคู่เอกสารที่มีฟิลด์อาร์เรย์ซึ่งมีอย่างน้อยหนึ่งองค์ประกอบตรงตามเกณฑ์การค้นหาทั้งหมดที่ระบุ

สร้างคอลเลกชันพร้อมเอกสาร:

> db.demo239.insertOne( 
...     { 
...         "Name" : "Chris", 
...         "details" : [ 
...             { "DueDate" : new ISODate("2019-01-21"), "ProductPrice" : 1270 }, 
...             { "DueDate" : new ISODate("2020-02-12"), "ProductPrice" : 2000 } 
...         ] 
...     } 
...); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e441c6bf4cebbeaebec5157") } 
> db.demo239.insertOne( 
...     { 
...         "Name" : "David", 
...         "details" : [ 
...             { "DueDate" : new ISODate("2018-11-11"), "ProductPrice" : 1450}, 
...             { "DueDate" : new ISODate("2020-02-12") } 
...         ] 
...     } 
...); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e441c6cf4cebbeaebec5158") }

แสดงเอกสารทั้งหมด:

> db.demo239.find();

ผลลัพธ์ - เอกสารที่สองมีรายการใน details ที่ไม่มี ProductPrice:

คำสั่งค้นหาเอกสารที่อาร์เรย์ details มีองค์ประกอบที่มี DueDate แต่ไม่มี ProductPrice:

> db.demo239.find({ 
    "details": { 
        "$elemMatch": { 
            "DueDate": { "$exists": true }, 
            "ProductPrice": { "$exists": false } 
        } 
    } 
})

ผลลัพธ์ - ได้เฉพาะเอกสารของ David ที่มีรายการไม่มี ProductPrice: