Update MongoDB Document by ID

  • Share this:

Code introduction


This function is used to update a document in a MongoDB collection by its ID. It takes a dictionary of update_values to specify the fields and values to be updated.


Technology Stack : PyMongoEngine

Code Type : Database operation

Code Difficulty : Intermediate


                
                    
def update_document_by_id(collection, document_id, update_values):
    # Update a document in a MongoDB collection by its ID
    result = collection.update_one({'_id': document_id}, {'$set': update_values})
    return result.modified_count