balaji
balaji

Reputation: 794

update an element of an array in mongo collection based on a condition met by another element in the same array

Below is my collection.

{
'_id': ObjectId('603fd4575250717d17aba89e'),
'user_id': 19,
'items': [
{

'price': 5,
'id': '342566b0d5f14117a228d8b17f215c4a'
},


 {


 'price': 5,
 'id': '09e12c647fdf4c409e934eac23c73789'
}
],

  }

I need to update the price for the element with the id 09e12c647fdf4c409e934eac23c73789, its current value is 5 and I need to update it to 6, may I know the query for the same please.

I tried with the below query and it did not work.

a = db.sample_collection.update_one({"items.$.id": "09e12c647fdf4c409e934eac23c73789"}, 
{"$set": {"items.$price": 6}})

Can someone help me on the correct query please.

Upvotes: 0

Views: 1195

Answers (2)

Md. Taiful Islam
Md. Taiful Islam

Reputation: 51

You should use $elemMatch to find the array index and $ operator to update the data of that index accordingly

db.collection.updateOne(
    {"items":{ "$elemMatch":{"id":"09e12c647fdf4c409e934eac23c73789"} }},
    { $set: { "items.$.price": 6 } }
)

Upvotes: 1

Montgomery Watts
Montgomery Watts

Reputation: 4034

The update query should look like this:

a = db.sample_collection.update_one({"items.id": "09e12c647fdf4c409e934eac23c73789"}, { "$set": { "items.$.price": 6 }})

This is an example of updating a document in an array. When performing an update, the positional operator, $ should only appear in the update document, not the query document.

Upvotes: 1

Related Questions