Cloud Stack Ninja

Assume we have documents like below:

{ "_id" : 1, "stock_item" : "almonds", warehouse: "B", "instock" : 120 },
{ "_id" : 2, "stock_item" : "pecans", warehouse: "A", "instock" : 80 },
{ "_id" : 3, "stock_item" : "almonds", warehouse: "B", "instock" : 60 },
{ "_id" : 4, "stock_item" : "cookies", warehouse: "B", "instock" : 40 },
{ "_id" : 5, "stock_item" : "cookies", warehouse: "A", "instock" : 80 }

The input is {stock_item: "almonds"} but we want to :

  1. find all documents that have {stock_item: "almonds"}
  2. retrieve the warehouse field of all documents returned in part 1
  3. return all documents that their warehouse field is included in part 2 as final result

So the final result would be like below because documents 1 and 3 have {stock_item: "almonds"} condition and both of them have {warehouse: "B"} so in result we want to return all documents that have {warehouse : "B"} :

{ "_id" : 1, "stock_item" : "almonds", warehouse: "B", "instock" : 120 },
{ "_id" : 3, "stock_item" : "almonds", warehouse: "B", "instock" : 60 },
{ "_id" : 4, "stock_item" : "cookies", warehouse: "B", "instock" : 40 }

I can do this by using two find queries respectively, but I was wondering How can I do this with mongodb aggregation in one query?



Read more here: https://stackoverflow.com/questions/64400861/mongodb-aggregation-retrieve-a-field-in-a-stage-and-use-it-in-another-stage

Content Attribution

This content was originally published by dzdmmtf at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: