我的第一个收藏值是:
coll1:
{
_id:"5f82f1618cfa6d290c6271a9",
name:"mehdi"
}
第二个收集值是:
coll2:
{
_id:"5f82f1618cfa6d290c6271aa",
fid:"5f82f1618cfa6d290c6271a9",
family:"parastar"
}
我如何基于coll1中的 _id 和coll2中的 fid 填充?
我想成为这样的结果
{
{
_id:"5f82f1618cfa6d290c6271aa",
fid:"5f82f1618cfa6d290c6271a9",
family:"parastar"
},
name:"mehdi"
}
您有这样做的主意吗?
答案 0 :(得分:0)
您必须以这种方式使用 $lookup
:
db.coll1.aggregate([
{
$lookup: {
from: "coll2",
localField: "_id",
foreignField: "fid",
as: "collection"
}
}
])
此查询使用您想要的数据创建一个名为 collection
的字段:
[
{
"_id": "5f82f1618cfa6d290c6271a9",
"collection": [
{
"_id": "5f82f1618cfa6d290c6271aa",
"family": "parastar",
"fid": "5f82f1618cfa6d290c6271a9"
}
],
"name": "mehdi"
}
]
示例here
使用Mongoose
也是一样,只写这样的查询:
var agg = await model.aggregate([
{
$lookup: {
from: "coll2",
localField: "_id",
foreignField: "fid",
as: "collection"
}
}
])
console.log(agg)