ใช้ $match กรองเอกสาร แล้ว $addFields ร่วม $filter เพื่อกรองสมาชิกในอาร์เรย์ตามช่วงราคา สร้างคอลเลกชันตัวอย่าง:
> db.demo351.insertOne({
"_id" : "101",
"ProductDetails" : [
{"ProductName" : "Product-1", "ProductPrice" : 500},
{"ProductName" : "Product-2", "ProductPrice" : 400}
]
});
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo351.insertOne({
"_id" : "102",
"ProductDetails" : [
{"ProductName" : "Product-3", "ProductPrice" : 200},
{"ProductName" : "Product-4", "ProductPrice" : 800}
]
});
{ "acknowledged" : true, "insertedId" : "102" }
แสดงข้อมูล:
> db.demo351.find();
คิวรีหาเอกสาร _id="102" แล้วกรอง ProductPrice ระหว่าง 600-900:
> db.demo351.aggregate([
{ $match: { _id: "102" } },
{ $addFields: {
ProductDetails: {
$filter: {
input: "$ProductDetails",
cond: {
$and: [
{ $gt: ["$$this.ProductPrice", 600] },
{ $lt: ["$$this.ProductPrice", 900] }
]
}
}
}
}}
])
ผลลัพธ์ (เหลือเฉพาะ Product-4 ราคา 800):
{ "_id" : "102", "ProductDetails" : [ { "ProductName" : "Product-4", "ProductPrice" : 800 } ] }
คำอธิบาย
$matchก่อน: ลดจำนวนเอกสารก่อนเข้า pipeline เร็วกว่า (ใช้ index ได้)$addFields: แทนที่ฟิลด์ ProductDetails ด้วยผลลัพธ์ที่กรองแล้ว$filter: วนลูปแต่ละสมาชิก ($$this) ตรวจสอบเงื่อนไข$andรวม$gtและ$ltสำหรับ range query