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

本小妞迷上赌 提交于 2020-01-14 07:00:08

问题


How can I search for the records filtering in a field that has an undefined value:

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

回答1:


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

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.




回答2:


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

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


来源:https://stackoverflow.com/questions/17088045/how-to-match-by-undefined-value-in-mongodb-aggregation-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!