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

ค้นหา Array ของ Objects ใน MongoDB ด้วย $unwind

การค้นหา Array ของ Objects ด้วย Aggregate

ใช่ สามารถค้นหา Array ของ Objects ได้ โดยใช้ $unwind ใน aggregate() ของ MongoDB สำหรับการจับคู่ ให้ใช้ $match

สร้าง Collection พร้อมข้อมูล

> db.demo623.insertOne(
...     {
...         _id:1,
...         details:[
...             {
...                 Name:"Chris"
...             },
...             {
...                 DueDate:new ISODate("2020-01-10")
...             },
...             {
...                 CountryName:"US"
...             }
...         ]
...     }
... );
{ "acknowledged" : true, "insertedId" : 1 }

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

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

ผลลัพธ์:

{
    "_id" : 1,
    "details" : [
        {
            "Name" : "Chris"
        },
        {
            "DueDate" : ISODate("2020-01-10T00:00:00Z")
        },
        {
            "CountryName" : "US"
        }
    ]
}

คิวรีค้นหา Array ของ Objects

> db.demo623.aggregate({$unwind: "$details"},
... {$match: {"details.Name":"Chris"}},
... {$project: {"details.Name": 1}})

ผลลัพธ์:

{ "_id" : 1, "details" : { "Name" : "Chris" } }