你可以使用:
查詢將是:
db.students.aggregate([{
"$group": {
"_id": "$class_id",
"grades": { "$push": "$grade" },
"students": { "$push": "$$ROOT" }
}
}, {
"$match": {
"grades": { "$all": ["blue","red"] }
}
}, {
"$unwind": "$students"
}, {
"$project": {
"_id": "$students._id",
"class_id": "$students.class_id",
"grade": "$students.grade",
}
}])
如果需要搭配其他顏色比[「藍」,「紅」]你可以在$match
聚集($in: ["blue","red","yellow"]
)
添加更多對於PyMongo實現它,這是非常簡單的:
from pymongo import MongoClient
import pprint
db = MongoClient().testDB
pipeline = [ <the_aggregation_query_here> ]
pprint.pprint(list(db.students.aggregate(pipeline)))
Additionnaly,只匹配屬於classes
收集學生,執行$lookup
並匹配那些不爲空。在聚合查詢中添加以下內容:
{
$lookup: {
from: "classes",
localField: "class_id",
foreignField: "class_id",
as: "class"
}
}, {
$match: {
"class": { $not: { $size: 0 } }
}
}