MongoEngine: How to update a document by ID

Updated: February 10, 2024 By: Guest Contributor Post a comment

Introduction

MongoEngine is a Document-Object Mapping (DOM) library for working with MongoDB from Python. It translates Python classes into MongoDB documents, providing an ORM-like layer on top of MongoDB. A common requirement in database operations is updating existing documents. In this tutorial, we will explore how to update a document by its ID using MongoEngine, proceeding from basic to advanced examples.

Setting Up

First, ensure that you have MongoEngine installed in your Python environment:

pip install mongoengine

Connect to your MongoDB instance:

from mongoengine import connect
connect('your_database_name', host='localhost', port=27017)

Define a simple document class:

from mongoengine import *

class User(Document):
    name = StringField()
    email = StringField()
    age = IntField()

Basic Update

To update a document by its ID, you first need to locate the document. The simplest way to do this is using the id field, which is automatically added to all documents:

user = User.objects(id='507f1f77bcf86cd799439011').modify(new=True, upsert=False, name='John Doe')

This code locates a User document by its ID and updates the name field to ‘John Doe’. The modify method returns the modified document if new=True, otherwise it returns None. Setting upsert=False ensures that a new document is not created if the ID does not exist.

Advanced Updates

For more complex updates, you might want to use the update_one method or the atomic update You need todifine the dictionary:

from mongoengine.queryset.base import CASCADE

User.objects(id='507f1f77bcf86cd799439011').update_one(set__name='Jane Doe', inc__age=1)

This code updates the document with the specified ID, changing the name to ‘Jane Doe’ and incrementing the age by 1. The set__ operator changes the value of a field, while the inc__ operator increments the value of a numerical field.

Conditional Updates

Sometimes, you may want to perform updates based on conditions. MongoEngine supports conditional operations using query operators:

User.objects(id='507f1f77bcf86cd799439011', age__lt=30).update_one(inc__age=5)

This code increments the age by 5 only if the existing age is less than 30. The age__lt=30 condition ensures that the update takes place under specific circumstances.

Bulk Updates

Updating multiple documents in one operation can significantly improve performance. Use the update method for bulk updates:

User.objects(age__gte=18).update(set__status='adult')

This example sets the status field to ‘adult’ for all User documents where the age is 18 or older. Notice that the update method without one applies the operation to all matching documents.

Upserting

An upsert operation updates a document if it exists or creates it if it doesn’t. To perform an upsert with MongoEngine:

User.objects(id='unique_id').update_one(upsert=True, set__name='New User')

This code tries to update a User document by its ID. If the document does not exist, MongoEngine will create a new document with the provided ID and name.

Using With Embedded Documents

If your documents include embedded documents, updating them requires a slightly modified approach. Consider a User document that includes an embedded list of addresses:

class Address(EmbeddedDocument):
    city = StringField()
    country = StringField()

class User(Document):
    name = StringField()
    email = StringField()
    addresses = ListField(EmbeddedDocumentField(Address))

User.objects(id='507f1f77bcf86cd799439011').update(push__addresses=Address(city='New York', country='USA'))

This code adds a new address to the specified user’s list of addresses. The push__ operator is used to add an item to a list.

Conclusion

Updating documents by ID in MongoEngine is versatile and can accommodate a wide range of requirements. By starting with the basics and progressively exploring more complex operations, you can effectively manage your documents in MongoDB using MongoEngine.