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

glinda93
  • 7,659
  • 5
  • 40
  • 78
Anand
  • 71
  • 9

1 Answers1

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}})
Belly Buster
  • 8,224
  • 2
  • 7
  • 20
  • db_update=db.mycollection.update_one({'_id': oid, 'array1': {'$elemMatch': { 'user': 'testUser1' }}}, {'$set': {'array1.$.age': 32}}) – Anand Jul 28 '20 at 17:19
  • I see the db_update.raw_result has this value {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True} – Anand Jul 28 '20 at 17:22
  • - DB is not getting updated with the new value. Am I missing something here? – Anand Jul 28 '20 at 17:23
  • Yes. It is the right database. I believe update_one saves it and do not additional mongo.db.myCollection.save() function. – Anand Jul 28 '20 at 18:39
  • Correct, you don't need `.save()`. – Belly Buster Jul 28 '20 at 21:39