分组mongoDB

时间:2019-02-07 18:43:47

标签: mongodb aggregation-framework

我在MongoDB中有一系列文档,如下所示:

{
    "playerId" : ObjectId("5c58363b5c226c24b0b37860"),
    "gameId" : ObjectId("5c59697f57ef0f512c1cb228"),
    "state" : 4
}

{
    "playerId" : ObjectId("5beab425c0d75e5afabc1638"),
    "gameId" : ObjectId("5c59697f57ef0f512c1cb228"),
    "state" : 4
}

我想进行汇总并得出以下结果:

{
    "_id" : ObjectId("5beab425c0d75e5afabc1638"), // the playerId
    "state" : 4,
    "opponents": ["","","",""] // all the opponents gameId
}

playerId分组,找到所有游戏,用户正在玩并获得所有对手playerId

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试以下汇总:

[m0, m1, m2, 0, m4, m5, m6, 0, m8, m9, m10, 0, m12, m13, m14, 1]

基本上,您需要从$group开始,这将为您提供每位玩家的所有游戏。然后,您可以使用$lookup将这些游戏与初始收藏合并。在下一步中,您可以使用$filter仅获取与对手有关联的文档(不包括与当前玩家具有相同db.col.aggregate([ { $group: { _id: "$playerId", games: { $push: "$gameId" } } }, { $lookup: { from: "col", localField: "games", foreignField: "gameId", as: "games" } }, { $project: { _id: 1, opponents: { $map: { input: { $filter: { input: "$games", cond: { $ne: [ "$$this.playerId", "$_id" ] } } }, in: "$$this.playerId" } } } } ]) 的文档)和$map仅获取_id s

打印:

playerId