MongoDB聚合返回空对象而不是null

时间:2020-03-22 19:27:33

标签: node.js mongodb aggregate

我目前在汇总时遇到问题 问题是,如果等级为空或不存在,则“等级”字段将返回空对象。我希望它返回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();

enter image description here

更改preserveNullAndEmptyArrays: false根本不会返回文档。 有办法解决吗?

谢谢!

1 个答案:

答案 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' }
    }
  }

看看是否适合您。

相关问题