Home > Software design >  Mongo array querying with an index
Mongo array querying with an index

Time:11-18

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.

CodePudding user response:

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

  • Related