Charles Johnson
Charles Johnson

Reputation: 741

MongoDB - How to find null value in nested array of objects

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

Upvotes: 0

Views: 1873

Answers (1)

Valijon
Valijon

Reputation: 13103

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

Upvotes: 3

Related Questions