需要返回得分超过60的总和,其中得分是数组JSON对象内的元素

时间:2017-10-16 07:35:21

标签: mongodb mongodb-query

我在MongoDB集合中的文档如下所示,JSON对象的数组 成绩 的长度各不相同:

dict_one = {'average' : 84, 'median' : 86.5, 'stdev' : 3.35}
dict_two = {'average' : 'B', 'median' : 'B+', 'stdev' : 'F'}
ds = [dict_one, dict_two]
d = {}
for k in dict_one.keys():
    d[k] = tuple(d[k] for d in ds)

print(d)

任务是编写MongoDB查询以返回分数总和大于60的集合。

1 个答案:

答案 0 :(得分:0)

以下是如何做到这一点:

db.collection.aggregate({
    $unwind: "$grades" // flatten the "grades" array
}, {
    $group: {
        "_id": "$_id",
        "sumOfScores": { // calculate the sum of all grades for all documents with the same "_id"
            $sum: "$grades.score"
        },
        "docs": {
            $push: "$$ROOT" // remember all affected documents per group
        }
    }
}, {
    $match: {
        "sumOfScores": {
            $gt: 60 // filter out everything that we don't care about
        }
    }
}, {
    $unwind: "$docs" // flatten the "docs" array
},  {
    $group: { // restore the original document structure
        "_id": "$docs._id",
        "address": { $first: "$docs.address" },
        "borough": { $first: "$docs.borough" },
        "cuisine": { $first: "$docs.cuisine" },
        "grades": {
            $push: "$docs.grades"
        },
        "name": { $first: "$docs.name" },
        "restaurant_id": { $first: "$docs.restaurant_id" }
    }
})