代码之家  ›  专栏  ›  技术社区  ›  Sanam

位置“$”没有更新数组中的正确值,而是创建新值?

  •  0
  • Sanam  · 技术社区  · 1 年前

    我需要在2个数组中$inc数量,然后返回更新后的文档。

    Mongodb文档

         _id: _id ***********
         quantity: [
          {
            "storage": "GODOWN",
            "qty": 1,
            "_id": "666e0f15876d5be1a8ce0a04"
          },
          {
            "storage": "SHOP",
            "qty": 0,
            "_id": "666e0f15876d5be1a8ce0a05"
          },
          {
            "storage": "GODOWN 2",
            "qty": 0,
            "_id": "666e0f15876d5be1a8ce0a06"
          }
        ],
         pricing: [{
            "firstAddedDate": "06/16/2024",
            "mrp": 0,
            "price": 0,
            "qty": 1,
            "total": 80,
            "default": true,
            "_id": "666e0f15876d5be1a8ce0a03"
          }]
    

    我需要增加定价数组的对象的数量,这些对象的值为'default:true。 这是代码-

    defualtPricingUpdated = await Item.findOneAndUpdate(
         { _id: newEntry.itemID, "pricing.default": true, "quantity._id": newEntry.storageID },
         { $inc: { "pricing.$.qty": Number(newEntry.qty), "quantity.$.qty": newEntry.qty, "pricing.$.total": newEntry.amount }},
         { returnDocument: "after" }
         ).session(session)
    

    因此,此命令在定价数组中创建一个新条目,而不是递增现有条目。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Yong Shun    1 年前

    从调查结果来看,当匹配 quantity 对象位置大于1,则会将新对象添加到 pricing 大堆

    因此,与合作 $[<identifier>] 过滤后的位置运算符将更准确。

    defualtPricingUpdated = await Item.findOneAndUpdate({
      _id: newEntry.itemID,
      "pricing.default": true,
      "quantity._id": newEntry.storageID
      
    },
    {
      $inc: {
        "pricing.$[p].qty": NumberInt(newEntry.qty),
        "quantity.$[q].qty": newEntry.qty,
        "pricing.$[p].total": newEntry.amount
      }
    },
    {
      arrayFilters: [
        {
          "p.default": true
        },
        {
          "q._id": newEntry.storageID  
        }
      ],
      returnDocument: "after"
    }).session(session)
    

    Demo @ Mongo Playground