6

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}}}
})

1 Answer 1

5

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}}}})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.