假设我有以下一组文件:
{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] }
{ "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] }
{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] }
{ "_id" : 4, "semester" : 2, "grades" : [ 79, 85, 80 ] }
{ "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92 ] }
{ "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96 ] }
如何查询以检索包含大于80的成绩的文档,包括仅包含查询中匹配项的成绩数组?鉴于上面的例子,我想检索以下结果集:
{ "_id" : 1, "semester" : 1, "grades" : [ 87, 90 ] } // 70 is missing
{ "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] }
{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] }
{ "_id" : 4, "semester" : 2, "grades" : [ 85, 80 ] } // 79 is missing
{ "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92 ] }
{ "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96 ] }
答案 0 :(得分:3)
您可以使用aggregation framework:
执行此操作db.collection.aggregate([
{
// Emit a new document for each grade in the "grades" field
"$unwind" : "$grades"
},
{
// Only emit documents whose "grades" field is at least 80
"$match" : {
"grades" : {
"$gte" : 80
}
}
},
{
// Group documents back together by original _id
"$group" : {
"_id" : "$_id",
"semester": {$first: "$semester"},
"grades" : {
"$push" : "$grades"
}
}
}
]);