kahoha
kahoha

Reputation: 185

How to merge result from $lookup with subdocuments

Consider the following toy example:

Collection shops

{
  "products": [
    { id: "abc", price: 20.5 },
    { id: "abd", price: 34.0 }
  ]
}

Collection products

{
  _id: "abc",
  name: "Apple"
}

Running the following query...

db.shops.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "products.id",
      foreignField: "_id",
      as: "product_info"
    }
  }
])

returns...

[{
  "products": [
    { id: "abc", price: 20.5 },
    { id: "abd", price: 34.0 }
  ],
  "product_info": [
    { _id: "abc", name: "Apple" },
    { _id: "abd", name: "Orange" }

  ]
}]

Is there a way to "merge" products and product_info to get the following?

[{
  "products": [
    { id: "abc", price: 20.5, name: "Apple" },
    { id: "abd", price: 34.0, name: "Orange" }
  ],
}]

Thanks for your help!

Upvotes: 1

Views: 37

Answers (1)

Ashh
Ashh

Reputation: 46441

You can use below aggregation

db.shops.aggregate([
  { $unwind: "$products" },
  {
    $lookup: {
      from: "products",
      localField: "products.id",
      foreignField: "_id",
      as: "products.name"
    }
  },
  { $unwind: "$products.name" },
  { $addFields: { "products.name": "$products.name.name" }},
  { $group: {
    _id: "$_id",
    products: {
      $push: "$products"
    }
  }}
])

Upvotes: 1

Related Questions