如何在MongoDB中使用数组更新特定元素的数组?

huangapple go评论77阅读模式
英文:

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

问题

我有一个对象

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

和一个数组,我只改变了产品名称

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

如何使用这个(updatedProduct)数组仅更新MongoDB中customer对象的产品名称。

我尝试使用$set,但它没有按预期工作。

英文:

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

答案1

得分: 1

以下是翻译好的代码部分:

    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"] },
                         ]
                      }
                   }
                }
             }
          }
       ]
    )
英文:

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"] },
                     ]
                  }
               }
            }
         }
      }
   ]
)

huangapple
  • 本文由 发表于 2023年3月12日 14:50:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定