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}}}
})
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.
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.
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>, ... } }
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.
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}}}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With