Home > Net >  How to update a object value when matched from an array in one mongodb document?
How to update a object value when matched from an array in one mongodb document?

Time:10-23

I have created a complex MongoDB document like this :

    {
      "_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
    }

Here you can see that ProductInfo is an array. My Document structure is

enter image description here

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

Now I have two things- id and seller

Actually here I want to do this- first, find by id, then filter productInfo by seller and update status to this particular seller. How can I do that ?

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

Please help me to do this. Can anyone help me?

**Note: Here I want to update only status value from a particular seller when matched find by document id.

CodePudding user response:

You can do it with positional operator - $:

db.collection.update({
  _id: ObjectId("6354129e0f5b15991649fd10"),
  "productInfo.seller": ObjectId("6354112f0f5b15991649fcfc"),
  
},
{
  "$set": {
    "productInfo.$.status": "New status"
  }
})

Working example

  • Related