Skip to content

Instantly share code, notes, and snippets.

@iJKTen
Last active March 9, 2021 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iJKTen/4144d8042471127ed00cc7423a059fad to your computer and use it in GitHub Desktop.
Save iJKTen/4144d8042471127ed00cc7423a059fad to your computer and use it in GitHub Desktop.

Query an array of embedded documents

If your inventosy document has the following data and you want to get all the warehouses with a value of 'A'

db.inventory.insertMany( [
   { 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: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

Run this query

db.inventory.find( { "instock.warehouse": "A"}, {'instock.warehouse.$': 1} )

The second parameter {'instock.warehouse.$': 1} is called a projection and I guess it tells mongo to return all matching warehouses with a value of A

Try the above query here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment