How can multiple documents be updated in bulk in MongoDB?
In MongoDB, you can use the updateMany() method to bulk update multiple documents. This method takes a query condition and an update operation as parameters, and then updates all documents that meet the query condition.
For example, if we have a collection named “users” with multiple documents, and we want to update the “role” field to “admin” for all documents with a status of “active”, we can use the following code:
db.users.updateMany(
{ status: "active" },
{ $set: { role: "admin" } }
)
In the code above, the first parameter { status: “active” } is the query condition used to match all documents with status as active; the second parameter { $set: { role: “admin” } } is the update operation used to update the role field of matched documents to admin.
The updateMany() method can efficiently bulk update multiple documents.