【发布时间】:2020-07-15 22:48:41
【问题描述】:
我正在努力解决一个烦人的问题。我在查询中使用聚合,我需要加入一些集合,输出必须是一个对象。这是我的代码...
usersModel.aggregate([
{
$match: { _id: ObjectId(req.params.id) }
},
{
$lookup: {
from: "agents",
as: "agent",
let: { "idAgent": "$agent" }, //$agent can be null
pipeline: [
{
$match: {
$expr: {
$eq: ['$_id', "$$idAgent"]
},
}
}
],
}
},
{ $unwind: { path: '$agent', preserveNullAndEmptyArrays: true } },
{
$addFields: {
agent: "$agent", //If $agent is null, it does not output the field agent...
}
}
])
如果在最后一个Stage中,字段$agent为null,$addFields不输出该字段。 还有其他方法可以做到吗?查找后我只需要代理字段作为对象。谢谢
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework