2

Consider the following document:

{
    "_id": 1,
    "properties": [
        {
            "key": "foobar",
            "value": null
        },
        {
            "key": "xxx",
            "value": "yyy"
        }
    ]
}

The properties are indexed:

db.collections.ensureIndex('properties')

I want to find all documents where the value for the key foobar is null.

While this query does find all elements where the value has the desired value:

db.collections.find({ properties: { key: 'xxx', value: 'yyy' } })

The following does not return any results:

db.collections.find({ properties: { key: 'foobar', value: null } })

Thanks for your help!

2 Answers 2

2

Use the $type operator that Ilan mentioned, but you need to use it with $elemMatch for it to work correctly in this case as otherwise $type won't be evaluated as an operator:

db.collections.find({properties: {
    $elemMatch: { key: 'foobar', value: { $type: 10 }}
}})
Sign up to request clarification or add additional context in comments.

Comments

0

Use the $type operator:

db.collections.find({ properties: { key: 'foobar', value: { $type: 10 } } })

From the docs:

The { cancelDate : { $type: 10 } } query matches documents that contains the cancelDate field whose value is null only; i.e. the value of the cancelDate field is of BSON Type Null (i.e. 10)

1 Comment

Thanks Ilan, although only 90 % correct. :-) Need to use $elemMatch as @JohnnyHK pointed out.

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.