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

前端 未结 3 612
走了就别回头了
走了就别回头了 2021-01-17 08:40

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

db.records.aggregate({
    $match: {
               


        
相关标签:
3条回答
  • 2021-01-17 09:25

    If you have fields that exist but are undefined you can search for them with null.

    db.records.aggregate({
        $match: {
            myField: {$exists: true, $eq: null},
        }
    })
    
    0 讨论(0)
  • 2021-01-17 09:35

    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.

    0 讨论(0)
  • 2021-01-17 09:38

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

    db.records.aggregate({
        $match: {
            myField: {'$type':6},
        }
    })
    
    0 讨论(0)
提交回复
热议问题