我刚刚开始学习 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) Friends 数组代表我的好友用户
2)games数组代表我玩过的游戏
我的 friend 会有相同的文档结构,游戏数组包含他们玩过的游戏
我想要的是按升序/降序或任何顺序列出我和我的 friend 之间最常见的游戏。
结果应如下所示
{
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 冠军。
最佳答案
您可以尝试以下聚合查询。
该查询将为每个 friend 游戏的 $unwind
friends
数组后面加上 $lookup
。
下一步是 $unwind
friendsgames
然后在 $project
阶段使用 $setIntersection
进行比较以找到输入文档 games
和每个 friendsgames
之间的常见游戏。
最后一步是通过games
$group
来收集玩相同游戏的好友
。
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"} } }
] )
关于javascript - 列出 friend 之间最常见的游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547797/