如何在mongodb聚合中检查子字段是否存在且不为空?

Mic*_*ski 8 mongoose mongodb aggregation-framework

我遇到了一个很烦人的问题,我似乎无法为我的特定情况找到任何解决方案。在我的 mongo 聚合管道中,我想添加一个字段,并且根据另一个字段的子字段的存在,我想分配该其他字段的子字段的值,如果该其他字段的子字段不存在,则为 1。

这是我尝试过的:

pipelineStages.push(
{$addFields: 
    {field: 
        {$cond: [
             {$ne: ["$otherField.subField", null]}, 
                    "$otherField.subField", 1]
             }
        }
     }
 );
Run Code Online (Sandbox Code Playgroud)

但是,它仅适用于该字段存在的情况。另一方面,该新字段根本没有添加到管道中。任何想法我做错了什么?

Joh*_*nn8 5

包裹$ifNull$cond是卓有成效的,甚至与子问题。

pipelineStages.push({
    $addFields: {
        newField: {
            $cond: [
                { 
                    "$ifNull": [ 
                        "$otherField.subField", 
                        false 
                    ] 
                },
                "$otherField.subField",
                1
            ]
        }
     }
 );
Run Code Online (Sandbox Code Playgroud)