Why mongodb finds this document ($ne: null for array)

Viewed 203

Data:

db.inventory.insertMany([
       { _id: 1, item: null },
       { _id: 2 },
       { _id: 3, item: 3 },
       { _id: 4 items: [1, 2, 3] },
       { _id: 5, items: [] }
    ])

Query 1:

db.inventory.find({ 'item': {$ne: null} })

Result 1:

{ _id: 3, item: 3 }

Query 2:

db.inventory.find({ 'items.0': {$ne: null} })

Result 2:

{ _id: 3, items: [1, 2, 3] },
{ _id: 4, items: [] }

Why mongoDB finds this document: { _id: 4, items: [] }? Is this a bug?

2 Answers

Use $exists: true instead of $ne: null.

$ne docs explain:

$ne selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.

  1. null itself a datatype in mongodb. this is why at the 0 index of items it is searching for a null value and not getting it. if you add null like items: [null] and run the query again you will not see _id: 4

  2. This is not a bug. this is how Mongo works.

  3. In your first result, the key item in the object itself does not exist. To satisfy 'item': {$ne: null} the key itself has to be present in the object. This is how javascript works as well. Check the JS Code.

  4. It also works with arrays. try: {'items.0': null} and {'items.0': {$ne: null}}, and you should see the difference.

Related