[英]Join two collection in mongoDB and extract out data in node js
I am using MongoDB 3.6 for my project. 我正在为项目使用MongoDB 3.6。 I have 2 collections "users" and "follow".
我有2个收藏集“用户”和“关注”。 I want to extract out details of user's followers and following (like an Instagram app).
我想提取用户关注者和关注者的详细信息(例如Instagram应用)。
users collection 用户集合
{
"id" : "1",
"name" : "abc",
"age" : "26"
},
{
"id" : "2",
"name" : "xyz",
"age" : "22"
},
{
"id" : "3",
"name" : "qwe",
"age" : "23"
}
follow collection 关注收藏
{
"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"
}
Now i want following list of id 2 So id 2 is following id 1 and id 3 So, Output should be like this 现在我想跟随id 2的列表,所以id 2跟在id 1和id 3之后。所以,输出应该像这样
{
"id" : "1",
"name" : "abc",
"age" : "26"
},
{
"id" : "3",
"name" : "qwe",
"age" : "23"
}
For that, I am using $lookup aggregation. 为此,我正在使用$ lookup聚合。 But this is not giving the desired output which I want.
但这没有给出我想要的期望输出。 Here is my code -
这是我的代码-
Follow.aggregate([
{
$lookup:{
from:"users",
localField:"id",
foreignField:"id",
as:"fromItems"
}
},
{
$replaceRoot:{newRoot: {$mergeObjects: [ { $arrayElemAt: ["$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project :
{
fromItems : 0
}
}
], callback)
To get following list of id 2
you can use following query: 要获取ID
2
以下列表,可以使用以下查询:
Follow.aggregate([
{
$match: { "id": "2" }
},
{
$lookup:{
from:"users",
localField:"follow id",
foreignField:"id",
as:"fromItems"
}
},
{
$replaceRoot:{newRoot: {$mergeObjects: [ { $arrayElemAt: ["$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project :
{
id : "$follow id",
name: 1,
age: 1
}
}
])
So the point here is that you have a relation between id
and follow id
and after $lookup
phase follow id
becomes the new id
since it's parent-child relation. 因此,这里的要点是您在
id
和follow id
之间具有关系,并且在$lookup
阶段之后, follow id
将成为新的id
因为它是父子关系。
EDIT: 3.4 solution below 编辑:下面的3.4解决方案
Follow.aggregate([
{
$match: { "id": "2" }
},
{
$lookup:{
from:"users",
localField:"follow id",
foreignField:"id",
as:"fromItems"
}
},
{
$project: {
id: "$follow id",
from: { $arrayElemAt: ["$fromItems", 0 ] }
}
},
{ $project :
{
id : 1,
name: "$from.name",
age: "$from.age"
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.