Petter Vinnberg
Petter Vinnberg

Reputation: 21

Possible to group multiple entries and form new object for the values?

I have Orders and Products being connected by a third collection with OrderID, ProductID, Quantity.

I want to get the result grouped something like this:

{
OrderID: 1,
products:[
name: productname1, quantity: 3
name: productname2, quantity: 1
]
},
{
OrderID: 2,
products:[
name: productname3, quantity: 10
name: productname5, quantity: 4
]
}

I have managed to $lookup and $project it down to displaying each coupling/reference on its own:

{
OrderID: 1,
name: productname1,
quantity: 3
},
{
OrderID: 1,
name: productname2,
quantity: 1
},
{
OrderID: 2
...
},
{
OrderID: 2
...
}

Is this to any use, or am i thinking wrong here? I basically tried $push into an object, but that doesn't really work.

Upvotes: 1

Views: 19

Answers (1)

Petter Vinnberg
Petter Vinnberg

Reputation: 21

Solved it after some head scratching.

Rearranged the last $project for this result instead:

{
OrderID: 1,
product: [{
   name: productname1,
   quantity: 3
   }]
}

I could then run this $group and get my desired result (pushing each entire object from array):

{
  _id: "$OrderID",
  products: {$push: "$product"}
}

Upvotes: 1

Related Questions