Reputation: 53
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}}}
})
Upvotes: 5
Views: 5294
Reputation: 75994
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}}}})
Upvotes: 4