In MongoDB, the updateMany
operation is used to update multiple documents within a collection based on a specified filter. This method is essential for making bulk modifications to documents in MongoDB collections.
db.collection.updateMany(filter, update, options)
The updateMany
method takes a filter
to specify which documents to update, an update
document to specify the modifications, and an optional options
parameter to customize the operation.
Let's look at some examples of how to use the updateMany
method in the programGuru
collection in MongoDB:
db.programGuru.updateMany(
{ age: { $gt: 30 } },
{ $set: { status: "senior" } }
)
This command finds all documents where the age
field is greater than 30 and updates the status
field to senior
.
db.programGuru.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "junior" } },
{ upsert: false }
)
This command finds all documents where the age
field is less than 30 and updates the status
field to junior
without inserting a new document if no match is found.
Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and updating multiple documents.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
This step involves inserting documents into the programGuru
collection.
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
We insert multiple documents into the programGuru
collection.
This step involves using the updateMany
method to update multiple documents in the programGuru
collection.
db.programGuru.updateMany(
{ age: { $gt: 30 } },
{ $set: { status: "senior" } }
)
We find all documents where the age
field is greater than 30 and update the status
field to senior
.
db.programGuru.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "junior" } },
{ upsert: false }
)
We find all documents where the age
field is less than 30 and update the status
field to junior
without inserting a new document if no match is found.
The MongoDB updateMany
operation is crucial for making bulk modifications to documents in collections. Understanding how to use this method allows you to efficiently manage and update data within MongoDB collections.