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!'. 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},
    }
})
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.