mongo聚合-为字段的不同组的值累加 [英] mongo aggregation - accumulate for different groups of values of a field
问题描述
如果我有Player
个格式的文件
{name: String, score: Int}
我有Group
个文档,其中的组代表球员列表
and I have Group
documents, where groups represent lists of players
{groupName: String, players: [ObjectID]}
玩家可以属于多个组.
我想对Player
个文档进行汇总,并按Group
分组(例如,使用一个汇总管道来获得每个组的球员得分总和).
I want to do an aggregation of Player
documents, grouped by Group
(ex. get the sums of players' scores for each group, with one aggregation pipeline).
我知道的选项:
=>给Player
文档返回指向它们所关联的Group
文档的指针,然后按GroupID
返回$group
.但我宁愿不必修改Player
集合. (也许有一种方法可以在管道中将GroupID
添加到文档中?)
=> give Player
docs back pointers to Group
documents they are a associated with, then $group
by GroupID
. But I prefer to not have to modify the Player
collection. (perhaps there is a way to "add in" GroupID
s to the docs during the pipeline?)
=>为每个组单独呼叫,并使用$match
阶段筛选仅要查询的当前组中的玩家.但是我更喜欢打一个简单的电话.
=> make a separate call for each group and use a $match
stage to filter to just players in the current group being queried for. But I prefer to make a single, simple call.
如何实现这种汇总? MongoDB聚合是否具有某些功能?
How can I achieve such an aggregation? Does MongoDB Aggregation have something that works for this?
(顺便说一下,将组和玩家彼此映射到进行呼叫的内存中不是问题.因此,涉及将玩家列表作为参数传递的选项确实是公平的游戏.)>
(By the way, it's not a problem to have the groups and players, mapped to each other, in memory where the call is being made. So options involving passing lists of players as arguments are indeed fair game.)
推荐答案
You could use the $lookup
operator for this. Consider running the following aggregation pipeline:
Mongo shell:
db.group.aggregate([
{ "$unwind": "$players" },
{
"$lookup": {
"from": "players",
"localField": "players",
"foreignField": "_id",
"as": "players_join"
}
},
{ "$unwind": "$players_join" },
{
"$group": {
"_id": {
"groupName": "$groupName",
"name": "$players_join.name"
},
"totalScore": { "$sum": "$players_join.score" }
}
}
])
您可以通过获取聚合框架包来添加对聚合的支持,该软件包为您包装了一些Mongo方法.只需流星添加 meteorhacks:aggregate
,您就可以开展业务.这将为您在Meteor中的集合添加一个汇总方法.
You can add support for aggregation by getting the aggregation framework package which wraps up some Mongo methods for you. Just meteor add meteorhacks:aggregate
and you should be in business. This will add an aggregate method to your collections in Meteor.
这篇关于mongo聚合-为字段的不同组的值累加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!