如何在一个mongodb文档中更新一个数组中匹配的对象值?

qyyhg6bp  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(166)

我创建了一个复杂的MongoDB文档,如下所示:

{
      "_id": {
        "$oid": "6354129e0f5b15991649fd10"
      },
      "orderId": "NEK-2209-06215614-79553",
      "user": {
        "$oid": "634d11565f254092fd666fd1"
      },
      "shippingAddress": {
        "$oid": "6353aaf0fa6a1b0124c22532"
      },
      "billingAddress": {
        "$oid": "6353aaf0fa6a1b0124c22532"
      },
      "productInfo": [
        {
          "seller": {
            "$oid": "634d784c723ee32fc178aa7a"
          },
          "products": [
            {
              "productId": {
                "$oid": "6353951e001ff50ea1a92602"
              },
              "quantity": 2,
              "variation": "M",
              "tax": 111
            }
          ],
          "price": 850,
          "status": "Pending"
        },
        {
          "seller": {
            "$oid": "6354112f0f5b15991649fcfc"
          },
          "products": [
            {
              "productId": {
                "$oid": "635411940f5b15991649fd02"
              },
              "quantity": 2,
              "variation": "M",
              "tax": 111
            }
          ],
          "price": 850,
          "status": "Pending"
        }
      ],
      "total": 1671,
      "shippingFees": 60,
      "couponDiscount": 10,
      "subtotal": 1721,
      "paymentInfo": {
        "paymentType": "Cash on Delivery"
      },
      "paymentMethod": "Home Delivery",
      "createdAt": {
        "$date": {
          "$numberLong": "1666454174641"
        }
      },
      "updatedAt": {
        "$date": {
          "$numberLong": "1666454174641"
        }
      },
      "__v": 0
    }

这里你可以看到ProductInfo是一个数组。

id: "id"
    productInfo: [
       {seller: "id", ....},
       {seller: "id", ....},
    ]

现在我有两个东西-idseller
实际上,我想这样做-首先,通过id查找,然后通过卖家过滤productInfo,并更新状态到这个特定的卖家。我该怎么做?

mydocument.findByIdAndUpdate(id, 
    //Here I have to write an update value to a particular seller from productInfo array.
    , {new: true})

请帮我做这件事。有人能帮我吗?

**注意:在这里,我只想更新状态值从一个特定的卖方匹配时,按文件ID查找。

bvjxkvbb

bvjxkvbb1#

您可以使用positional operator - $执行此操作:

db.collection.update({
  _id: ObjectId("6354129e0f5b15991649fd10"),
  "productInfo.seller": ObjectId("6354112f0f5b15991649fcfc"),

},
{
  "$set": {
    "productInfo.$.status": "New status"
  }
})

Working example

相关问题