Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb query nested array documents where property not null

Tags:

I am trying to get all the documents where at least one element of the instock collection has the warehouse field not null. Expected result: discard only the last documents.

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

This query discards the 3 and 4.

db.getCollection('inventory').find({
    $and: [{"instock.warehouse": {$ne: null}}, {"instock.warehouse": {$exists: true}}]
})

This one returns all the elements

db.getCollection('inventory').find({
    "instock": {$elemMatch: {"warehouse": {$ne: null}, "warehouse": {$exists: true}}}
})
like image 592
Ediel Cardona Avatar asked Mar 21 '18 20:03

Ediel Cardona


People also ask

How do I query a nested document in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

How do I specify NOT NULL in MongoDB?

To query for is not null value, we can use the $ne operator as well as the $eq operator and specify the desired value that we want to query for. This guide aims to provide readers with different ways and examples for the same to query for is not null values in MongoDB.

How do I query an array element in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do you find documents with a matching item in an embedded array?

Use $match With $eq to Find Matching Documents in an Array in MongoDB. Use $match With $all to Find Matching Documents in an Array in MongoDB.


1 Answers

Use below find query.

Note the use of $elemMatch & $ne which compares all the elements of array i.e. includes all the documents where instock array don't have at least one null value in warehouse field.

db.inventory.find({"instock":{"$elemMatch":{"warehouse":{"$ne":null}}}})
like image 192
s7vr Avatar answered Sep 20 '22 12:09

s7vr