【发布时间】:2018-08-16 00:20:17
【问题描述】:
我在我的项目中使用 MongoDB 3.6。 我有 2 个集合“用户”和“关注”。我想提取用户关注者和关注者的详细信息(如 Instagram 应用程序)。
用户集合
{
"id" : "1",
"name" : "abc",
"age" : "26"
},
{
"id" : "2",
"name" : "xyz",
"age" : "22"
},
{
"id" : "3",
"name" : "qwe",
"age" : "23"
}
关注收藏
{
"id" : "2",
"follow id" : "1"
},
{
"id" : "3",
"follow id" : "1"
},
{
"id" : "1",
"follow id" : "2"
},
{
"id" : "2",
"follow id" : "3"
},
{
"id" : "1",
"follow id" : "3"
}
现在我想要下面的 id 2 列表所以 id 2 跟随 id 1 和 id 3 所以,输出应该是这样的
{
"id" : "1",
"name" : "abc",
"age" : "26"
},
{
"id" : "3",
"name" : "qwe",
"age" : "23"
}
为此,我正在使用 $lookup 聚合。但这并没有给出我想要的输出。 这是我的代码-
Follow.aggregate([
{
$lookup:{
from:"users",
localField:"id",
foreignField:"id",
as:"fromItems"
}
},
{
$replaceRoot:{newRoot: {$mergeObjects: [ { $arrayElemAt: ["$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project :
{
fromItems : 0
}
}
], callback)
更多了解请参考image
【问题讨论】:
标签: javascript node.js mongodb mean-stack