Mongo DB 嵌套数组 $set 来更新文档

问题描述 投票:0回答:1

这是我的文件 请让我知道如何更新 cart.sizeQuantity.数量值 它应该更新productId匹配的值,然后检查尺寸匹配,然后更新

{
  "name": "user",
  "email": "[email protected]",
  "password": "***************",
  "cart": [
    {
      "productId": "1253456912854",
      "sizeQuantity": [
        {
          "size": "Large",
          "quantity": 2
        }
      ]
    },
    {
      "productId": "1253456912855",
      "sizeQuantity": [
        {
          "size": "Large",
          "quantity": 2
        },
        {
          "size": "X-Large",
          "quantity": 2
        }
      ]
    }
  ],
  "__v": 0
}

我尝试过这样做,但这没有用

const hasSize = await this.findOne({
    _id: userId,
    "cart.productId": productId,
    "cart.sizeQuantity.size": productSize,
  });
  if (hasSize) {
await this.updateOne(
    {
      _id: userId,
      cart: { $elemMatch: { productId: productId } },
      "cart.sizeQuantity.size": productSize,
    },
    {
      $set: {
        "cart.$.sizeQuantity.quantity": 4,
      },
    }
  );

  }
  
mongodb mongoose multidimensional-array mongodb-query
1个回答
0
投票

链接 arrayFilters 以更新嵌套的数组元素。更多用法请参阅官方文档

db.collection.update({
  _id: 1,
  "cart.productId": "1253456912854",
  "cart.sizeQuantity.size": "Large"
},
{
  $set: {
    "cart.$[c].sizeQuantity.$[sq].quantity": 4
  }
},
{
  arrayFilters: [
    {
      "c.productId": "1253456912854"
    },
    {
      "sq.size": "Large"
    }
  ]
})

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.