I have below kind of data in my mongo database:
[
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "G", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "G", qty: 35 } ] }
]
I want to find all matching document that has warehouse as G. The instock
array should contain only the matching element. Basically, the output should look like below:
[{ item: "paper", instock: [ { warehouse: "G", qty: 15 } ] },
{ item: "postcard", instock: [ { warehouse: "G", qty: 35 } ] }
]
I have written below query:
db.collection_name.find({"instock.warehouse":"G"});
Above query returns required documents, but it gives all elements of instock
array, which I don't want.
How can I write such query which gives me desired documents with only matching elements of instock array?
Thank You!:)