ใช้ $project ร่วมกับ $unwind และตั้งค่าฟิลด์ที่ไม่ต้องการเป็น 0
$unwind แยกอาร์เรย์ แล้ว $match กรอง แล้ว $project เลือกฟิลด์ที่ต้องการ (1) และไม่ต้องการ (0)
สร้างข้อมูลตัวอย่าง
> db.demo731.insertOne({
"ProductInformation": [
{ ProductId:"Product-1", ProductPrice:80 },
{ ProductId:"Product-2", ProductPrice:45 },
{ ProductId:"Product-3", ProductPrice:50 }
]
});
แสดงข้อมูลทั้งหมด
> db.demo731.find();
ผลลัพธ์:
{ "_id" : ObjectId("5eac5efd56e85a39df5f6341"), "ProductInformation" : [ { "ProductId" : "Product-1", "ProductPrice" : 80 }, { "ProductId" : "Product-2", "ProductPrice" : 45 }, { "ProductId" : "Product-3", "ProductPrice" : 50 } ] }
คิวรีแสดงเฉพาะ ProductId ที่มีราคา 80
> db.demo731.aggregate([
{ $unwind: "$ProductInformation" },
{ $match: { "ProductInformation.ProductPrice": 80 } },
{ $project: {_id: 0, "ProductInformation.ProductPrice":0} }
])
ผลลัพธ์: แสดงเฉพาะ ProductId
{ "ProductInformation" : { "ProductId" : "Product-1" } }