不太确定您的文档结构,但是如果您有 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 }