列出朋友之间最常见的游戏



我刚刚开始学习mongodb,所以我对查询的选择目前还不错。因此,我将直接解决问题。以下是我每个用户的文档

{
    id:"14198959",
    user_name:"kikStart2X"
    friends:[
                {
                    friend_id:"1419897878",
                    friend_name:"nitpick",
                    profile_picture:"some image data",
                },
                {
                        friend_id:"14198848418",
                        friend_name:"applePie",
                        profile_picture:"some image data",
                }, //etc
            ],
    games:[
            {
                game_id:"1" , 
                game_name:"Bunny Hop"
            },
            {
               game_id:"2" , 
               game_name:"Racing cars",
            },
          ],
}

现在,该集合具有所有文档具有相同的结构

1(朋友数组代表我的朋友

2(游戏阵列代表我玩过的游戏

我的朋友将拥有相同的文档结构,其中包含他们玩过的游戏

的游戏阵列

我想要的是在我和我的朋友之间列出上升/下降或任何订单的最常见游戏。

结果应该看起来像以下

{
    result:
    [
        {
            game_id:"1" , 
            game_name:"Bunny Hop",
            friends:
            [
                {
                        friend_id:"1419897878",
                        friend_name:"nitpick",
                        profile_picture:"some image data",
                },
                {
                        friend_id:"14198848418",
                        friend_name:"applePie",
                        profile_picture:"some image data",
                },
            ]
        },
        {
            game_id:"2" , 
            game_name:"Racing cars",
            friends:
            [
                {
                        friend_id:"71615343",
                        friend_name:"samuel",
                        profile_picture:"some image data",
                },
            ]
        }
    ]
}

我知道这很难实现,但我不知道该怎么做,并搜索了互联网数小时。事先感谢您所有的MongoDB冠军。

您可以尝试以下集合查询。

查询将$unwind friends数组跟踪每个朋友游戏的$lookup

下一步是$unwind friendsgames,然后在$project阶段使用$setIntersection进行比较,以查找输入文档gamesfriendsgames中的每一个之间的常见游戏。

最后一步是通过games到CC_11进行使用相同游戏收集friends

db.collection.aggregate( [
   { $unwind:"$friends" },     
   {
      $lookup: {
         from: collectionname,
         localField: "friends.friend_id",
         foreignField: "id",
         as: "friendsgames"
        }
   },
   { $unwind:"$friendsgames" },
   { $project:{commongames:{$setIntersection:["$games", "$friendsgames.games"]}, friends:1  }},
   { $unwind:"$commongames" },
   { $group:{_id:"$commongames", friends:{$push:"$friends"} } }    
] )

最新更新