【发布时间】:2020-06-30 05:14:04
【问题描述】:
我正在尝试使用聚合函数从两个文档中获取数据。我能够做到,但我正在寻找解决方案,如何仅在查找表中应用 $project
下面是我的方法
app.get('/getAllDetailById',(req,res)=>{
if(db){
// lookup
db.collection("points").aggregate(
[
{ "$addFields": { "enquiry_by": { "$toObjectId": "$enquiry_by" }}},
{
"$lookup" : {
from: "user",
localField: "enquiry_by",
foreignField: "_id",
as: "userDetails"
}
},
{ $unwind: "$userDetails"},
]
).toArray()
.then(result=>{
console.log(result[0])
}).catch(err=>{
res.send(err)
})
}
})
我想要的是从点表和用户表中获取所有字段,我只想要名称和用户名。我使用了 $project 但它只返回在此定义的字段。
{ $project: {"userDetails.name":1, "userDetails.username":1,"_id":0} }
有没有什么方法可以单独为用户表申请$project
【问题讨论】:
-
这能回答你的问题吗? $project in $lookup mongodb
-
您只能在投影中指定 排除字段 - 这将保留您需要的所有字段。