Python – MongoDB – Update

Python - MongoDB - Update

In MongoDB, the update() method performs an update operation on a specified document or documents of a collection. We can use update() method to update a single document or multiple documents. In this tutorial, we will learn how to update documents in MongoDB using Python.

Prerequisites

  • Python
  • PyMongo Driver
  • MongoDB Database

Connect to a Database

To use PyMongo, we must first import it. We can import PyMongo like this:

import pymongo

For our examples, we will assume a database named ‘testdb’ with a collection named ‘customers’ in MongoDB. Here’s how we can connect to MongoDB and testdb database:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

Updating a Single Document

We can update a single document of a collection in MongoDB using update_one() method. The update_one() method finds the first document in the collection that matches the query and updates it.

Here’s an example:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Update a single document
customers.update_one({'name': 'John'}, {'$set': {'age': 45}})

This replaces the value of the age field with 45 for the first document in the “customers” collection where the name field is equal to “John”.

The first argument to update_one() specifies the filter to match the document that needs to be updated. The second argument is the update operation to be performed.

The update operation is specified using the $set operator which sets the value of a field in the document. In our example, we are setting the value of the “age” field to 45.

The update_one() method returns an instance of UpdateResult class which contains information about the update operation such as the number of documents modified.

Let’s see how to retrieve this information:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Update a single document
result = customers.update_one({'name': 'John'}, {'$set': {'age': 45}})

print(result.modified_count)

This will print the number of documents modified which should be 1 in our example.

Updating Multiple Documents

We can update multiple documents of a collection in MongoDB using update_many() method. The update_many() method updates all documents in the collection that match the specified filter.

Here’s how to use the update_many() method:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Update multiple documents
customers.update_many({'city': 'London'}, {'$set': {'country': 'UK'}})

This sets the value of the “country” field to “UK” for all documents in the “customers” collection where the “city” field is equal to “London”.

The first argument to update_many() specifies the filter to match the documents that need to be updated. The second argument is the update operation to be performed.

The update operation is specified using the $set operator which sets the value of a field in the document. In our example, we are setting the value of the “country” field to “UK”.

The update_many() method returns an instance of UpdateResult class which contains information about the update operation such as the number of documents modified.

Let’s see how to retrieve this information:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Update multiple documents
result = customers.update_many({'city': 'London'}, {'$set': {'country': 'UK'}})

print(result.modified_count)

This will print the number of documents modified.

Updating Documents using Update Operators

In MongoDB, we can use update operators to perform more complex update operations. Update operators provide a way to update specific fields or elements within an array field.

Here are some of the commonly used update operators:

  • $set – Set the value of a field in a document
  • $unset – Remove a field from a document
  • $inc – Increment the value of a field in a document
  • $push – Add an element to an array field in a document
  • $addToSet – Add an element to an array field in a document only if it does not already exist
  • $pull – Remove an element from an array field in a document

$set Operator

The $set operator sets the value of a field in a document. If the field does not already exist, $set operator will add the field to the document with the specified value.

Let’s see how to use the $set operator:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Update a single document using $set operator
customers.update_one({'name': 'John'}, {'$set': {'age': 45}})

In this example, we have updated a single document using the $set operator by setting the value of the “age” field to 45 for the document where the “name” field is equal to “John”. If the “age” field does not exist in the document, the $set operator will add the “age” field to the document with the specified value.

$unset Operator

The $unset operator removes a field from a document.

Let’s see how to use the $unset operator:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Remove the "age" field from the document where the "name" is "John"
customers.update_one({'name': 'John'}, {'$unset': {'age': ''}})

In this example, we have removed the “age” field from the document where the “name” field is equal to “John”.

$inc Operator

The $inc operator increments the value of a field by a specified amount.

Let’s see how to use the $inc operator:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Increment the value of the "age" field by 1 for the document where the "name" is John
customers.update_one({'name': 'John'}, {'$inc': {'age': 1}})

In this example, we have incremented the value of the “age” field by 1 for the document where the “name” field is equal to “John”.

$push Operator

The $push operator adds an element to an array field in a document. If the field does not already exist, $push operator will add the field to the document as an array with the specified value as its first element.

Let’s see how to use the $push operator:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Add a new item to the "orders" array for the document where the "name" is John
customers.update_one({'name': 'John'}, {'$push': {'orders': 'item_4'}})

In this example, we have added a new item to the “orders” array for the document where the “name” field is equal to “John”. If the “orders” field does not exist in the document, the $push operator will add the “orders” field to the document as an array with “item_4” as its first element.

$addToSet Operator

The $addToSet operator adds an element to an array field in a document only if it does not already exist in the array. If the field does not already exist, $addToSet operator will add the field to the document as an array with the specified value as its first element.

Let’s see how to use the $addToSet operator:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Add a new item to the "orders" array if it does not already exist for the document where the "name" is John
customers.update_one({'name': 'John'}, {'$addToSet': {'orders': 'item_4'}})

In this example, we have added a new item to the “orders” array for the document where the “name” field is equal to “John” only if it does not already exist in the array. If the “orders” field does not exist in the document, the $addToSet operator will add the “orders” field to the document as an array with “item_4” as its first element.

$pull Operator

The $pull operator removes an element from an array field in a document.

Let’s see how to use the $pull operator:

import pymongo

# Connect to MongoDB instance running on localhost
client = pymongo.MongoClient('mongodb://localhost:27017/')

# Select the "testdb" database
db = client['testdb']

# Select the "customers" collection
customers = db['customers']

# Remove the item "item_3" from the "orders" array for the document where the "name" is John
customers.update_one({'name': 'John'}, {'$pull': {'orders': 'item_3'}})

In this example, we have removed the item “item_3” from the “orders” array for the document where the “name” field is equal to “John”.

Conclusion

In this tutorial, we learned how to update documents in MongoDB using PyMongo. We learned how to update a single document and multiple documents in a collection using the update_one() and update_many() methods respectively. We also learned how to perform more complex update operations using update operators such as $set, $unset, $inc, $push, $addToSet, and $pull operators.

Leave a Reply

Your email address will not be published. Required fields are marked *