如何通过 MongoDB 聚合框架中的“未定义”值进行匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17088045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:17:19  来源:igfitidea点击:

How to match by 'undefined' value in MongoDB Aggregation Framework?

mongodbaggregation-frameworknosql

提问by BreakPhreak

How can I search for the records filtering ina field that has an undefinedvalue:

如何具有undefined值的字段中搜索记录过滤:

db.records.aggregate({
    $match: {
        myField: "undefined",
    }
})

回答by user854301

Filter it by $type:6, (mongodb referece, note that this type marked as 'deprecated'):

过滤它$type:6,(mongodb 引用注意这个类型被标记为 'deprecated'):

db.records.aggregate({
    $match: {
        myField: {'$type':6},
    }
})

回答by ixe013

If you want to filter out documents that have some fields missing, use the $existsoperator.

如果要过滤掉缺少某些字段的文档,请使用$exists运算符。

This works on my machine :

这适用于我的机器:

> db.test.drop()
true
> db.test.insert( {'Hello':'World!', 'myField':42})
> db.test.insert( {'Hello again':'World!'})
> db.test.aggregate({'$match':{ 'myField':{'$exists':false} }})
{
        "result" : [
                {
                        "_id" : ObjectId("51b9cd2a6c6a334430ec0c98"),
                        "Hello again" : "World!"
                }
        ],
        "ok" : 1
}

The document that has myField present does not show in the results.

存在 myField 的文档不会显示在结果中。