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

วิธีการใช้อาร์เรย์เป็นตัวกรองโดยการสืบค้นเอกสารย่อยใน MongoDB?


สำหรับสิ่งนี้ ให้ใช้ $setIsSubset ใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสาร -

> db.demo407.insertOne(
...    {
...       Name:"Chris",
...       "details" : [
...          {
...             id:100
...          },
...          {
...             id:110
...          },
...          {
...             id:130
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70dffe15dc524f70227677")
}

แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -

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

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{
   "_id" : ObjectId("5e70dffe15dc524f70227677"),
   "Name" : "Chris",
   "details" : [
      {
         "id" : 100
      },
      {
         "id" : 110
      },
      {
         "id" : 130
      }
]

ต่อไปนี้เป็นแบบสอบถามเพื่อใช้อาร์เรย์เป็นตัวกรองโดยการสืบค้นเอกสารย่อย -

> db.demo407.aggregate([
...    {$match: { }},
...    {$project: {
...       "details": {
...          $filter: {
...             input: "$details",
...             as: "output",
...             cond: { $setIsSubset: [["$$output.id"],[100, 130]] }
...       }
...    }
... }}])

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{ "_id" : ObjectId("5e70dffe15dc524f70227677"), "details" : [ { "id"