Sling Academy
Home/Python/MongoEngine: How to update a document by ID

MongoEngine: How to update a document by ID

Last updated: February 10, 2024

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.

Next Article: MongoEngine: How to delete documents by a condition

Previous Article: MongoEngine: How to insert one or multiple documents

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types