ใช้ aggregation pipeline ร่วม $match, $addFields, $filter, $expr เพื่อ query array of embedded documents ตามช่วงค่า สร้างคอลเลกชันตัวอย่าง:
> db.demo346.insertOne({
_id: 101,
userDetails: [
{UserName: "Chris", Score:78},
{UserName: "David", Score:68},
{UserName: "Bob", Score:88}
]
});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo346.insertOne({
_id: 102,
userDetails: [
{UserName: "Mike", Score:92},
{UserName: "Sam", Score:62},
{UserName: "Carol", Score:97}
]
});
{ "acknowledged" : true, "insertedId" : 102 }
แสดงข้อมูล:
> db.demo346.find();
คิวรีกรอง userDetails ที่ Score อยู่ระหว่าง 80-99:
> db.demo346.aggregate([
{ "$match": { "$expr": { "$gte": [{ "$size": { "$ifNull": ["$userDetails", []] } }, 1] }}},
{ "$addFields": {
"userDetails": {
"$filter": {
"input": { "$ifNull": ["$userDetails", []] },
"cond": {
"$and": [
{ "$gte": ["$$this.Score", 80] },
{ "$lte": ["$$this.Score", 99] }
]
}
}
}
}}
])
ผลลัพธ์:
{ "_id" : 101, "userDetails" : [ { "UserName" : "Bob", "Score" : 88 } ] }
{ "_id" : 102, "userDetails" : [ { "UserName" : "Mike", "Score" : 92 }, { "UserName" : "Carol", "Score" : 97 } ] }
คำอธิบาย
$matchแรก: กรองเอกสารที่ userDetails มีสมาชิกอย่างน้อย 1 ($size+$ifNullป้องกัน null)$addFields: แทนที่ userDetails ด้วยผลลัพธ์ที่ filter แล้ว$filter: วนลูป $$this ตรวจสอบ Score ในช่วง 80-99$ifNull: ป้องกัน error หาก userDetails เป็น null หรือ missing