Saif Ali Khan
Saif Ali Khan

Reputation: 848

Unwind in mongodb

I am doing aggregation for creating invoice. So I have 3 collections invoice, pitchedProduct and products. In my invoice I have the pitchedProduct Id so by using it I am able to access PitchedProduct collection and in my pitchedProduct collection I have product Id so to access product Id I have to first unwind the pitchedProduct output to access its inner elements. But by doing so the invoice data which is projected is also shared in multiple objects.Is it possible that I can query without unwind so that duplicate date does not create.

here is my query

db.invoices.aggregate([

  { $lookup : { from: "productsPitched", localField:"pid", foreignField:
    "idx", as:"pitchedProduct"  }},

  { $unwind: "$pitchedProduct" },

  { $lookup : { from: "products", localField:"pitchedProduct.pid", foreignField: "idx", as:"products"  } },

  { $project:{idx: true, pid: true, pmt: true, amtc: true, isv: true, dt:true,

   products: {idx: true, nm: true },

   pitchedProduct: { idx: true, pid: true}}}
] )

And the output I am getting is

{ "_id" : ObjectId("58fde1e14afe1e3578b3ff86"), "pmt" : [ 30 ], "pid" : 

[ 87 ], "amtc" : 19550, "isv" : false, "dt" : 1493033441840, "idx" : 30, "products" : [ { "idx" : 2, "nm" : "garuda" } ] }
{ "_id" : ObjectId("58fde2704afe1e3578b3ff89"), "pmt" : [ 31, 32 ], "pid" : [ 86, 75 ], "amtc" : 143750, "isv" : false, "dt" : 1493033584309, "idx" : 31, "products" : [ { "nm" : "Garuda Lite", "idx" : 1 } ] }
{ "_id" : ObjectId("58fde2704afe1e3578b3ff89"), "pmt" : [ 31, 32 ], "pid" : [ 86, 75 ], "amtc" : 143750, "isv" : false, "dt" : 1493033584309, "idx" : 31, "products" : [ { "nm" : "Garuda Lite", "idx" : 1 } ] }

I want to access pitchedProduct data without unwinding it because as I unwind it the whole data is converted into multiple objects which is not a good solution.

How can I achieve this??

Feel free to ask any questions if you don't understand..

Thank you :)

Upvotes: 0

Views: 153

Answers (1)

s7vr
s7vr

Reputation: 75914

There are couple of ways to resolving the problem but the below solution is more applicable to your case.

You can use $addFields which will extract the product pitched pid's instead of $unwind. So this way you can directly pass the pitchedproductpid to the $lookup just similar to the way you did for pid in first $lookup.

Something like below

db.invoices.aggregate([
  { $lookup : { from: "productsPitched", localField:"pid", foreignField:"idx", as:"pitchedProduct"  }},
  { $addFields : {pitchedproductpid:"$pitchedProduct.pid"}},
  { $lookup : { from: "products", localField:"pitchedproductpid", foreignField: "idx", as:"products"  } },
  { $project:{idx: true, pid: true, pmt: true, amtc: true, isv: true, dt:true,products: {idx: true, nm: true },pitchedProduct: { idx: true, pid: true}}}
] )

Upvotes: 1

Related Questions