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

ค้นหาเอกสารที่ทุกองค์ประกอบในอาร์เรย์มีค่าเฉพาะใน MongoDB

ใช้ $not ร่วมกับ $elemMatch และ $ne เพื่อค้นหาเอกสารที่ ทุก องค์ประกอบในอาร์เรย์มีค่าเท่ากับที่กำหนด เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.findDocumentsDemo.insertOne(
  { _id: 101, "ProductDetails": [ { "ProductValue":100 }, { "ProductValue":120 } ] }
);
{ "acknowledged" : true, "insertedId" : 101 }
> db.findDocumentsDemo.insertOne(
  { _id: 102, "ProductDetails": [ { "ProductValue":120}, { "ProductValue":120 }, { "ProductValue":120 } ] }
);
{ "acknowledged" : true, "insertedId" : 102 }

แสดงเอกสาร:

> db.findDocumentsDemo.find().pretty();

คิวรี่ค้นหาเอกสารที่ ทุก ProductValue ใน ProductDetails เป็น 120:

> db.findDocumentsDemo.find({
  "ProductDetails.ProductValue" : { },
  "ProductDetails" : {
    $not : {
      $elemMatch : {
        "ProductValue" : { $ne : 120 }
      }
    }
  }
});

ตรรกะ: $not { $elemMatch: { ProductValue: { $ne: 120 } } } หมายถึง "ไม่มีองค์ประกอบไหนที่ ProductValue ไม่เท่ากับ 120" = "ทุกองค์ประกอบ ProductValue เท่ากับ 120"

บรรทัด "ProductDetails.ProductValue" : { } ต้องมีไว้ (แม้ว่าง) เพื่อบังคับให้ MongoDB ตรวจสอบฟิลด์นี้ (ป้องกันกรณีที่ฟิลด์หายไป)