mongodbpymongopymongo-3.xflask-pymongo

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


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


Solution

  • 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}})