如何在 mongoDB 中使用 $cond 而不使用 else 表达式?

Ric*_*h S 2 mongodb

如果 site!= 'undefined',我想将 $site 的值添加到变量中,否则我必须跳过该文档并继续下一个文档。

我用了

{$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site"}}}

但它返回“$cond 缺少'else'参数”

如果我添加一个 else 语句

1){$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site", else: {} }}}

它将值返回到 addset {Object Object}

2){$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site", else: null }}}

它向集合返回 null,如 ["sample1", "sample2", ]

3){$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site", else: "" }}}

它将 null 返回给集合,如 ["sample1", "sample2", "" ]

如果不满足条件,我不希望将任何内容添加到集合中。

Sar*_*non 8

从 MongoDB 3.6 开始,您可以使用$$REMOVE变量作为运算符ELSE的参数$cond,以防止在条件失败时将任何内容添加到集合中。

请参阅此处,了解 Mongo Docs 中的示例。

对于您的情况,我们可以通过以下方式完成:

{
    $group: {
            //_id: <group-by-expression>
            // other fields (if any)..
            sites: {
                $addToSet: { 
                    $cond: {
                        if: { $ne: ["$site", 'undefined'] },
                        then: "$site",
                        else: "$$REMOVE"
                    }
                }
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者

{
    $group: {
            //_id: <group-by-expression>
            // other fields (if any)..
            sites: {
                $addToSet: { 
                    $cond: [
                        { $ne: ["$site", 'undefined'] },
                        "$site",
                        "$$REMOVE"
                    ]
                }
            }
    }
}
Run Code Online (Sandbox Code Playgroud)