Search code examples
databasemongodbmongoosemongodb-query

How can I update specific elements in an array in MongoDB using an array


I have an object

customer = {
  customerName:"Rajesh",
  customerNum:"899111111111",
  products:[
    { 
      productName:"ABC",
      productPrize:"100",
      deliveyDate:"20/2/2022"
    },{ 
      productName:"def",
      productPrize:"22",
      deliveyDate:"22/2/2022"
    }
  ]
}

and I have an array where I changed the product names only :

updatedProduct = [ { productName:"cdf"},{ productName:"qqq"} ]

How can I update only product names of the customer object in MongoDB using this( updatedProduct ) array.

I tried the use $set but it didn't worked as expected


Solution

  • You can try this one:

    updatedProduct = [{ productName: "cdf" }, { productName: "qqq" }]
    db.customer.udpateOne(
       { customerName: "Rajesh" },
       [
          {
             $set: {
                products: {
                   $map: {
                      input: { $range: [0, updatedProduct.length, 1] },
                      as: "i",
                      in: {
                         $mergeObjects: [
                            { $arrayElemAt: ["$products", "$$i"] },
                            { $arrayElemAt: [updatedProduct, "$$i"] },
                         ]
                      }
                   }
                }
             }
          }
       ]
    )