0

If I have documents that look like this:

  {
    "items": [
      {
        "key": null
      }
    ]
  },
  {
    "items": [
      {
        "key": 2
      }
    ]
  }
]

... how can I find the document with 'key' set to null?

This is the query I've been trying, but I don't understand why it's returning both documents:

db.collection.find({
  "items.0.key": {
    $eq: null
  }
})

1 Answer 1

3

null not only matches itself but also matches “does not exist.” Thus, querying for a key with the value null will return all documents

https://www.oreilly.com/library/view/mongodb-the-definitive/9781449344795/ch04.html#sect2_d1e4021

Workaround: We need to perform a query with $type operator.

db.collection.find({
  "items.0.key": {
    $type: 10
  }
})

MongoPlayground

Sign up to request clarification or add additional context in comments.

5 Comments

That works, but I should have explained that I'm looking for this document only if the items array contains only one object.
@CharlesJohnson updated my answer, please check again
I still don't understand. Why would $eq: null return the second document when items.0.key clearly exists and is not null ? And the rest of the quote is > Thus, querying for a key with the value null will return all documents lacking that key
@aaaaaa This is due to a MongoDB issue jira.mongodb.org/browse/SERVER-27442. Essentially it is ambiguous what is meant by "items.0.key", since 0 can be the index of an item in an array or the key of any object in that array.
wow what a stupid design

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.