20

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

db.records.aggregate({
    $match: {
        myField: "undefined",
    }
})
1
  • 2
    How do you define undefined ? You mean something like $exists ? If possible, add a sample document and a regular query that would return it. Looking at your question, 'undefined' is a string, just like 'Hello, World!'.
    – ixe013
    Commented Jun 13, 2013 at 13:25

3 Answers 3

51

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

db.records.aggregate({
    $match: {
        myField: {'$type':6},
    }
})
1
  • 8
    Thanks for this. The accepted answer doesn't seem to actually answer the question but this does and is amazingly useful give that if you try to search for undefined it tells you that you can't.
    – Chris
    Commented Feb 6, 2015 at 11:44
27

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.

1
  • 8
    The $type operator is also available to search for fields with null values (there's also a deprecated undefined type). This FAQ entry explains querying for nulls and/or missing fields (the same operators are available for the aggregation framework) . For example :db.test.aggregate({'$match':{ 'myField':{'$type':10} }}) would match documents that have a myField defined but its value is null.
    – jimoleary
    Commented Jun 13, 2013 at 17:01
2

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},
    }
})

Not the answer you're looking for? Browse other questions tagged or ask your own question.