Sling Academy
Home/Python/PyMongo: How to update and delete documents

PyMongo: How to update and delete documents

Last updated: February 08, 2024

Introduction

PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python. This tutorial will focus on how to update and delete documents in a MongoDB database using PyMongo. Whether you’re a beginner or seasoned developer, understanding these operations is crucial for manipulating data effectively in your applications.

Prerequisites

Before you begin, ensure that you have both MongoDB and PyMongo installed and properly configured on your system. You should be familiar with basic Python programming and have a fundamental understanding of MongoDB concepts like documents and collections.

Basic Operations

Connecting to the Database

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['test_database']

Updating a Single Document

The simplest form of update operation is updating a single document. The update_one method is used for this purpose. Here’s how you can change the name of a user from ‘John’ to ‘Jonathan’:

result = db.users.update_one({'name': 'John'}, {'$set': {'name': 'Jonathan'}})
print(f"Modified count: {result.modified_count}")

Deleting a Single Document

Just as with updates, MongoDB also supports deleting single documents. The delete_one method is used for this. To delete a user named ‘John’:

result = db.users.delete_one({'name': 'John'})
print(f"Deleted count: {result.deleted_count}")

Advanced Operations

Updating Multiple Documents

To update multiple documents at once, PyMongo provides the update_many method. For instance, if you want to increment the age of all users by 1:

result = db.users.update_many({}, {'$inc': {'age': 1}})
print(f"Modified count: {result.modified_count}")

Deleting Multiple Documents

Similarly, to remove all users whose age is over 30:

result = db.users.delete_many({'age': {'$gt': 30}})
print(f"Deleted count: {result.deleted_count}")

Conditional Updates

It’s also possible to perform updates based on certain conditions. Let’s say you want to promote users to ‘admin’ if their age is over 18 but below 60:

result = db.users.update_many({'age': {'$gt': 18, '$lt': 60}}, {'$set': {'role': 'admin'}})
print(f"Modified count: {result.modified_count}")

Using Upsert

An upsert operation updates documents if they exist or inserts them if they do not. The update_one and update_many methods both accept an upsert parameter for this purpose. Here’s an example:

result = db.users.update_one({'name': 'Michael'}, {'$set': {'name': 'Michael', 'role': 'user'}}, upsert=True)
print(f"Upserted ID: {result.upserted_id}")

Bulk Write Operations

For performing multiple update and delete operations in a single command, you can use the bulk_write method. This is useful for optimizing network usage and database load. Here’s an example sequence:

from pymongo import UpdateOne, DeleteOne, BulkWriteResult
operations = [
    UpdateOne({'name': 'John'}, {'$set': {'name': 'Jonathan'}}),
    DeleteOne({'name': 'Michael'})
]
result = db.users.bulk_write(operations)
print(f"Bulk operation result: {result.bulk_api_result}")

Error Handling and Best Practices

While working with update and delete operations, it’s essential to handle potential errors effectively. Utilize try-except blocks to catch exceptions such as PyMongoError. Additionally, always ensure data consistency and integrity when performing database mutations.

Conclusion

Updating and deleting documents are fundamental operations in MongoDB that can be easily handled with PyMongo. By understanding and correctly applying the methods discussed in this tutorial, you can manipulate your MongoDB data efficiently, ensuring your applications perform optimally and accurately reflect your data’s state.

Next Article: How to translate MongoDB shell syntax to PyMongo code

Previous Article: Python sqlite3: Write a program to benchmark query execution time

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots