1

Can someone explain this behavior?

db.inventory.insertMany( [
   { item: "journal", instock: [ { warehouse: "A", qty: null }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

Copied from https://docs.mongodb.com/v4.2/tutorial/query-array-of-documents/

but the first item, instock.0.qty is replaced with null.

Consequently, this query produces strange results:

> db.inventory.find({"instock.0.qty": null})
{ "_id" : ObjectId("6194329212c7421dbaaeac81"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : null }, { "warehouse" : "C", "qty" : 15 } ] }
{ "_id" : ObjectId("6194329212c7421dbaaeac82"), "item" : "notebook", "instock" : [ { "warehouse" : "C", "qty" : 5 } ] }
{ "_id" : ObjectId("6194329212c7421dbaaeac83"), "item" : "paper", "instock" : [ { "warehouse" : "A", "qty" : 60 }, { "warehouse" : "B", "qty" : 15 } ] }
{ "_id" : ObjectId("6194329212c7421dbaaeac84"), "item" : "planner", "instock" : [ { "warehouse" : "A", "qty" : 40 }, { "warehouse" : "B", "qty" : 5 } ] }
{ "_id" : ObjectId("6194329212c7421dbaaeac85"), "item" : "postcard", "instock" : [ { "warehouse" : "B", "qty" : 15 }, { "warehouse" : "C", "qty" : 35 } ] }

EDIT: I'm expecting only one result, yet they all come back.

2
  • Actually, you inserts null ibb.co/bBBDVjK Commented Nov 16, 2021 at 22:54
  • Yea, that was intentional. I'm only expecting one result in the query, yet all the documents are returned. Commented Nov 16, 2021 at 23:00

1 Answer 1

1

A similar issue was reported in this Jira ticket: Incorrect filter result when using a null match inside an indexed array field.

The proposed suggestion was using $type to check the value which is null.

db.collection.find({
  "instock.0.qty": {
    $type: "null"
  }
})

Sample Mongo Playground

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.