在MongoDB中聚合值数组

时间:2016-01-27 22:43:01

标签: mongodb

我有一个我希望按id分组的值数组,并获取所有值的总和。目前我正在尝试:

db.entries.aggregate(
[
    { $match: {"user": "John" } },
    { "$unwind": '$games'},
    { $group: {
        "_id": "$games.id",
        "score": { "$sum": "$games.score"} }},
])

数据如下:

{  
   "user":"john",
   "games":[  
      {  
         "id":123,
         "score":123
      }
   ]
},
{  
   "user":"john",
   "games":[  
      {  
         "id":123,
         "score":123
      }
   ]
},
{  
   "user":"john",
   "games":[  
      {  
         "id":256,
         "score":256
      }
   ]
}

在这个例子中,对于" John"我想获得所有独特游戏分数的总和。在这个例子中我应该得到(123 + 256)。

但是,现在我得到了各个游戏的总和,而不是所有游戏的总和。

1 个答案:

答案 0 :(得分:0)

我在这里:

> db.entries.find();
{ "_id" : ObjectId("56a9610cca390d7e14a54486"), "user" : "john", "games" : [ { "id" : 123, "score" : 123 } ] }
{ "_id" : ObjectId("56a9610cca390d7e14a54487"), "user" : "john", "games" : [ { "id" : 123, "score" : 123 } ] }
{ "_id" : ObjectId("56a9610cca390d7e14a54488"), "user" : "john", "games" : [ { "id" : 256, "score" : 256 } ] }
> db.entries.aggregate([ {$match: {user: "john"}}, {$unwind: "$games"}, {$group: {_id: "$games.id", score: {$sum: "$games.score"}}} ]);
{ "_id" : 256, "score" : 256 }
{ "_id" : 123, "score" : 246 }

有什么问题?