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

คิวรี่ MongoDB หาค่าที่ซ้ำกันในอาร์เรย์

ใช้ตัวดำเนินการ $where ร่วมกับฟังก์ชัน JavaScript เพื่อหาเอกสารที่มีค่าซ้ำกันในอาร์เรย์ เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.sameValueMultipleTimesDemo.insertOne(
  { "ListOfPrice":[ {"Price": 110}, {"Price":130}, {"Price": 145} ] }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cefc4e6ef71edecf6a1f6b9") }
> db.sameValueMultipleTimesDemo.insertOne(
  { "ListOfPrice":[ {"Price": 110}, {"Price":178}, {"Price": 110} ] }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cefc4e7ef71edecf6a1f6ba") }

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

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

คิวรี่หาเอกสารที่มี Price = 110 ซ้ำมากกว่า 1 ครั้ง:

> db.sameValueMultipleTimesDemo.find({
  "$where": function() {
    return this.ListOfPrice.filter(function(p) {
      return p.Price == 110;
    }).length > 1;
  }
})

คำอธิบาย: ฟังก์ชันใน $where ใช้ filter() กรองเฉพาะออบเจกต์ที่ Price = 110 แล้วตรวจสอบ length > 1 วิธีนี้ยืดหยุ่นแต่ใช้ JavaScript engine อาจช้าบนข้อมูลขนาดใหญ่