how can we join arrays in mongodb with nodejs?

You can try,

  • $lookup using pipeline, pass saved_products in let
  • $unwind deconstruct Products array
  • $match product id
  • $mergeObjects to merge business fields and product fields
  • $replaceRoot to replace merged object in root
db.user.aggregate([
  {
    $lookup: {
      from: "business",
      let: { saved_products: "$saved_products" },
      pipeline: [
        { $unwind: "$Products" },
        { $match: { $expr: { $in: ["$Products._id", "$$saved_products"] } } },
        {
          $replaceRoot: {
            newRoot: {
              $mergeObjects: [
                "$Products",
                {
                  _business_id: "$_id",
                  business_name: "$name",
                  location: "$location"
                }
              ]
            }
          }
        }
      ],
      as: "saved_products"
    }
  }
])

Playground

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top