MongoDB的分组

问题描述 投票:1回答:1

我有一系列的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

有什么想法吗?

mongodb aggregation-framework
1个回答
2
投票

你可以试试下面汇总:

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"
                }
            }
        }
    }
])

基本上你需要启动$group这将给大家每一个球员的比赛。然后你可以使用$lookup合并与最初收集这些游戏。在接下来的步骤就可以使用$filter只得到文件与对手(排除具有相同的_id为当前玩家的那些)和$map只得到playerIds

打印:

{ "_id" : ObjectId("5beab425c0d75e5afabc1638"), "opponents" : [ ObjectId("5c58363b5c226c24b0b37860") ] }
{ "_id" : ObjectId("5c58363b5c226c24b0b37860"), "opponents" : [ ObjectId("5beab425c0d75e5afabc1638") ] }
© www.soinside.com 2019 - 2024. All rights reserved.