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

ดึง Element เฉพาะจาก Embedded Array ใน MongoDB

การดึง Element เฉพาะจาก Embedded Array

เพื่อดึง Element เฉพาะ ให้ใช้ $match ร่วมกับ Dot Notation

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

> db.demo641.insert(
...     {
...         ProductId:101,
...         "ProductInformation":
...         [
...             {
...                 ProductName:"Product-1",
...                 "ProductPrice":1000
...             },
...             {
...                 ProductName:"Product-2",
...                 "ProductPrice":500
...             },
...             {
...                 ProductName:"Product-3",
...                 "ProductPrice":2000
...             },
...             {
...                 ProductName:"Product-4",
...                 "ProductPrice":3000
...             }
...         ]
...     }
... );
WriteResult({ "nInserted" : 1 })

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

> db.demo641.find();

ผลลัพธ์:

{
    "_id" : ObjectId("5e9c31d46c954c74be91e6e2"),
    "ProductId" : 101,
    "ProductInformation" : [
        { "ProductName" : "Product-1", "ProductPrice" : 1000 },
        { "ProductName" : "Product-2", "ProductPrice" : 500 },
        { "ProductName" : "Product-3", "ProductPrice" : 2000 },
        { "ProductName" : "Product-4", "ProductPrice" : 3000 }
    ]
}

คิวรีดึง Element ที่ ProductPrice เป็น 1000 หรือ 2000

> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty();

ผลลัพธ์:

{
    "ProductInformation" : {
        "ProductName" : "Product-1",
        "ProductPrice" : 1000
    }
}
{
    "ProductInformation" : {
        "ProductName" : "Product-3",
        "ProductPrice" : 2000
    }
}