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

MongoDB: ค้นหาค่าในอาร์เรย์ด้วยหลายเงื่อนไข (Range) ด้วย $elemMatch

ใช้ $elemMatch ร่วม $gt และ $lt ใน aggregation เพื่อค้นหาเอกสารที่มีสมาชิกในอาร์เรย์อยู่ในช่วงที่กำหนด สร้างคอลเลกชันตัวอย่าง:

> db.demo341.insertOne({
  "Name": "Chris",
  "productDetails" : [
    { "ProductPrice" : { "Price" : 800 } },
    { "ProductPrice" : { "Price" : 400 } },
    { "ProductPrice" : { "Price" : 300 } }
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e53ed5cf8647eb59e5620a7") }
> db.demo341.insertOne({
  "Name": "Chris",
  "productDetails" : [
    { "ProductPrice" : { "Price" : 1000 } },
    { "ProductPrice" : { "Price" : 1200 } },
    { "ProductPrice" : { "Price" : 1300 } }
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e53edc1f8647eb59e5620a8") }

แสดงข้อมูล:

> db.demo341.find();

คิวรีหาเอกสารที่มี ProductPrice.Price อยู่ระหว่าง 600-900:

> db.demo341.aggregate([
  { "$match": {
    "productDetails": {
      "$elemMatch": {
        "ProductPrice.Price": { "$gt": 600, "$lt": 900 }
      }
    }
  }}
]).pretty();

ผลลัพธ์ (ได้เอกสารแรกที่มี Price 800):

{ "_id" : ObjectId("5e53ed5cf8647eb59e5620a7"), "Name" : "Chris", "productDetails" : [ { "ProductPrice" : { "Price" : 800 } }, { "ProductPrice" : { "Price" : 400 } }, { "ProductPrice" : { "Price" : 300 } } ] }

ทำไมต้องใช้ $elemMatch?

  • หากใช้ {"productDetails.ProductPrice.Price": {$gt: 600, $lt: 900}} จะจับคู่เอกสารที่มี สมาชิกต่างกัน** ตรงเงื่อนไขแยกกัน (เช่น ตัวหนึ่ง > 600, อีกตัว < 900)
  • $elemMatch บังคับให้ สมาชิกตัวเดียว ตรงเงื่อนไขทั้งหมดพร้อมกัน
  • เหมาะสำหรับ query บน array of embedded documents