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

วิธีค้นหา Array ที่ตรงกันแม้ลำดับต่างกันใน MongoDB

การค้นหา Array Match แบบ Exact แต่ไม่สนลำดับใน MongoDB

เมื่อต้องการค้นหาเอกสารที่มี array field ตรงตามค่าที่กำหนดทั้งหมด แต่ไม่สนใจลำดับของค่าใน array ใช้การรวม $all และ $size operators

ตัวอย่างการสร้างคอลเลกชันและเพิ่มข้อมูล

> db.exactMatchArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentGameScores":[45,78,98]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c94702d6669774125246c") }
> db.exactMatchArrayDemo.insertOne({"StudentName":"Chris","StudentAge":23,"StudentGameScores":[45,78]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c94a42d6669774125246d") }

แสดงข้อมูลทั้งหมด

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

ผลลัพธ์:

{ "_id" : ObjectId("5c9c94702d6669774125246c"), "StudentName" : "David", "StudentAge" : 22, "StudentGameScores" : [ 45, 78, 98 ] }
{ "_id" : ObjectId("5c9c94a42d6669774125246d"), "StudentName" : "Chris", "StudentAge" : 23, "StudentGameScores" : [ 45, 78 ] }

ค้นหา Array ที่มีค่า 45 และ 78 เท่านั้น (ขนาด 2)

> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 2, "$all": [ 78, 45 ] } }).pretty();

ผลลัพธ์ (พบเฉพาะ Chris):

{ "_id" : ObjectId("5c9c94a42d6669774125246d"), "StudentName" : "Chris", "StudentAge" : 23, "StudentGameScores" : [ 45, 78 ] }

ค้นหา Array ที่มีค่า 45 และ 78 รวมอยู่ (ขนาด 3 ไม่สนลำดับ)

> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 3, "$all": [ 78, 45 ] } }).pretty();

ผลลัพธ์ (พบ David ที่มีค่า 45, 78, 98):

{ "_id" : ObjectId("5c9c94702d6669774125246c"), "StudentName" : "David", "StudentAge" : 22, "StudentGameScores" : [ 45, 78, 98 ] }

คำอธิบาย Operators

  • $all : ต้องมีค่าทุกตัวที่ระบุใน array (ไม่สนลำดับ)
  • $size : กำหนดขนาดของ array ให้ตรงตามที่ต้องการ
  • การรวมใช้งาน: $all + $size = ค้นหา array ที่มีค่าครบทุกตัวที่ระบุ และมีขนาดเท่ากับที่กำหนด (Exact match)

ตัวอย่างเพิ่มเติม

// ค้นหา array ที่มีค่า 1, 2, 3 ครบ และขนาดเท่ากับ 3
db.collection.find({ "field": { "$all": [1,2,3], "$size": 3 } })

// ค้นหา array ที่มีค่า 1, 2 อย่างน้อย (อาจมีค่าอื่นเพิ่มได้)
db.collection.find({ "field": { "$all": [1,2] } })

เทคนิคนี้มีประโยชน์เมื่อต้องการค้นหาข้อมูลที่ tags หรือ categories ตรงกันแม้จะเรียงลำดับต่างกัน