You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中仅当文档含指定字段时才投影对象?

解决方案

可以使用MongoDB的$cond条件操作符,根据字段是否存在(或非空)来决定返回完整对象还是空值。结合你已经执行过$unwind(启用preserveNullAndEmptyArrays)的情况,修改后的投影操作如下:

{
    '$project': {
        '_id': 1,
        'applicationIds': {
            '$cond': {
                'if': '$applicationIds',
                'then': {
                    'type': 'linux',
                    'refId': '$applicationIds'
                },
                'else': null
            }
        },
        'configurationIds': {
            '$cond': {
                'if': '$configurationIds',
                'then': {
                    'type': 'linux',
                    'refId': '$configurationIds'
                },
                'else': null
            }
        }
    }
}

说明

  • $cond会判断if条件:如果$applicationIds存在且非空(因为unwind后要么是单个值要么是null),则执行then分支,生成包含type和refId的对象;
  • 如果$applicationIds不存在或为null,则执行else分支,返回null(即你想要的“为空”效果);
  • configurationIds的逻辑完全一致。

这样修改后,当字段无记录时,对应的字段值会是null,而不是只保留type: 'linux'的不完整对象。

内容的提问来源于stack exchange,提问作者TheStranger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:17:05