2

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?

0

2 Answers 2

2

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.

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

3 Comments

docs.mongodb.com/manual/tutorial/query-for-null-fields In this example, the query db.inventory.find ({item: null}) displays a document without item. Why does this not work with arrays?
I don't know, you can ask on developer.mongodb.com/community/forums.
0
  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.

2 Comments

But why the first result is missing document { _id: 2 }.
docs.mongodb.com/manual/tutorial/query-for-null-fields In this example, the query db.inventory.find ({item: null}) displays a document without item. Why does this not work with arrays?

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.