0

I was trying to project a field in an array.

For example in below example

db.inventory.insertMany( [
  { item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
  { item: "notebook", status: "A",  size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
  { item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
  { item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
  { item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

I need final output of warehouse list as below based on find search with item: "postcard.

expected output

["B", "C"]

Update

And in our code, I need to get the array of the hashString for below data. enter image description here

user1595858
  • 3,700
  • 15
  • 66
  • 109
  • You are actually looking for [`.distinct()`](https://docs.mongodb.com/manual/reference/method/db.collection.distinct/) as in `db.inventory.distinct("instock.warehouse",{ "item": "postcard"})`. It's purpose is for exactly what you are asking here. – Neil Lunn Aug 07 '17 at 00:13
  • @NeilLunn That was easy, I have updated the example thought that i could apply same solution as `db.inventory.distinct("services.email.verificationTokens.hashString", {_id: ObjectId("5987801f6d2b152a6ed9beb5")}) ` but didn't work as expected. – user1595858 Aug 07 '17 at 00:26
  • I'd say "Welcome to StackOverflow" but you are not exactly new here. What you calling "updating the example" is what I actually call **changing the question from what was asked**. But what you **should** have asked in a "new question" is actually easily answered by "your document structure is not actually what you think it is". Because the correct path is `db.inventory.distinct("services.email.verificationTokens.0.has‌​hString", {_id: ObjectId("5987801f6d2b152a6ed9beb5")})`. Which indicates to be that you have incorrect code writing that entry. – Neil Lunn Aug 07 '17 at 00:31
  • Since nobody has made this clear enough to you in the past I'll attempt to convey it clearly. **Do not change the actual question asked once answered or marked as a duplicate**. When you actually have different data to what you ask in a question your actions instead should be **1.** You should have included the **real** data in the original question. **2.** You actually spend more than 5 minutes attempting to apply the new knowledge and read referenced documentation. **3.** Failing both of those [Ask a new Question](https://stackoverflow.com/questions/ask) instead. – Neil Lunn Aug 07 '17 at 00:35
  • @NeilLunn Definitely I should ask a new question as the commented solution was not working as well. I will do some more research and try to create a question if required. – user1595858 Aug 07 '17 at 00:39

0 Answers0