我目前在汇总时遇到问题 问题是,如果等级为空或不存在,则“等级”字段将返回空对象。我希望它返回null,而不是空对象。
const query = await this.db.collection('users').aggregate([
{ $match: { ...filter } },
{ $lookup: { from: 'ranks', localField: 'rank', foreignField: '_id', as: 'rank' } },
{ $unwind: { path: '$rank', preserveNullAndEmptyArrays: true } },
{ $project: this.getProjectionFields(fields) }
]).toArray();
更改preserveNullAndEmptyArrays: false
根本不会返回文档。
有办法解决吗?
谢谢!
答案 0 :(得分:0)
您可以尝试在$cond
阶段使用$project
,它将评估rank
是否为空对象,返回null,否则返回该字段的值。
// create project stage to return null if field is an empty object
$project: {
...projectOtherUserFields,
rank: {
$cond: { if: { $eq: ['$rank', {}] }, then: null, else: '$rank' }
}
}
看看是否适合您。