1

Update a single array item with matching id and one of the array element using Pymongo

Tried few Pymongo commands one using array_filters(not sure whether this works with only 1 array level depth) but looks like nothing is updating even though there is no error reported but the update is not happening.

What is the right Pymongo command to update the below?

{
        "_id" : ObjectId("9f1a5aa4217d695e4fe56be1"),
    
        "array1" : [
                {
                        "user" : "testUser1",            
                        "age" : 30,                    
                }
        ],
}
new_age_number = 32
mongo.db.myCollection.update_one({"_id": id}, {"$set": {"array1.$[i].age": new_age_number}}, array_filters=[{"i.user":"testUser1"}],upsert=False)


update_db = mongo.db.myCollection.update({"_id": id, "array1[index].user":"testUser1"}, {"$set": {"item_list[index].age": new_age_number}}, upsert=False)

mongo.db.myCollection.save(update_db)

*index is the number from for loop

1 Answer 1

2

Review the documentation here: https://docs.mongodb.com/manual/reference/operator/update/positional/#update-documents-in-an-array

Noting specifically:

Important

You must include the array field as part of the query document.

So, if you want to update the first item in the array:

oid = ObjectId("9f1a5aa4217d695e4fe56be1")
db.mycollection.update_one({'_id': oid, 'array1.user':  'testUser1' }, {'$set': {'array1.$.age': 32}})

If you want to update a specific item in the array:

oid = ObjectId("9f1a5aa4217d695e4fe56be1")
db.mycollection.update_one({'_id': oid, 'array1': {'$elemMatch': { 'user':  'testUser1' }}}, {'$set': {'array1.$.age': 32}})
Sign up to request clarification or add additional context in comments.

5 Comments

db_update=db.mycollection.update_one({'_id': oid, 'array1': {'$elemMatch': { 'user': 'testUser1' }}}, {'$set': {'array1.$.age': 32}})
I see the db_update.raw_result has this value {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
- DB is not getting updated with the new value. Am I missing something here?
Yes. It is the right database. I believe update_one saves it and do not additional mongo.db.myCollection.save() function.
Correct, you don't need .save().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.