0

我有 4 名球员在不同的比赛中得分。例如

{user: score} -- json keys
{'a': 10}, {'a':12}, {'b':16}

我试图找出一种方法,我可以使用聚合函数找到单人游戏的总和。

users.aggregation([{$match:{'user':'a'}},{$group:{_id: null, scores:{$sum:'$score'}])

我也在为 b 重复同样的事情并继续

在镜头中,我为不同的用户做同样的事情太多次了。

什么是最好的方式或不同的方式或优化方式,所以我可以为所有用户编写一次聚合查询

4

3 回答 3

1

您可以将所需的内容users$in子句匹配,然后按照@Sourbh Gupta 的建议进行分组。

db.users.aggregate([
{$match:{'user':{$in: ['a', 'b', 'c']}}},
{$group:{_id: '$user', scores:{$sum:'$score'}}}
])
于 2016-12-20T08:19:13.880 回答
0

根据用户对数据进行分组。IE

 users.aggregation([{$group:{_id: "$user", scores:{$sum:'$score'}}}])
于 2016-12-20T07:12:57.293 回答
0

不太确定您的文档结构,但是如果您有 2 个不同字段的 2 个不同分数,您可以组合在一起然后求和,然后投影和求和然后 2 个分组总和(如果这有意义的话)

例如,我有这些文件:

> db.scores.find()
{ "_id" : ObjectId("5858ed67b11b12dce194eec8"), "user" : "bob", "score" : { "a" : 10 } }
{ "_id" : ObjectId("5858ed6ab11b12dce194eec9"), "user" : "bob", "score" : { "a" : 12 } }
{ "_id" : ObjectId("5858ed6eb11b12dce194eeca"), "user" : "bob", "score" : { "b" : 16 } }

请注意,我们有一个用户bob,他有 2xa分数和 1xb分数。

我们现在可以编写一个聚合查询来为 bob 进行匹配,然后对分数求和。

db.scores.aggregate([
    { $match: { user : "bob" } },
    { $group: { _id : "$user", sumA : { $sum : "$score.a" }, sumB : { $sum : "$score.b" } } },
    { $project: { user: 1, score : { $sum: [ "$sumA", "$sumB" ] } } }
]);

这将为我们提供以下结果

{ "_id" : "bob", "score" : 38 }
于 2016-12-20T08:41:21.913 回答