Updating multiple records in MongoDB can be done using the updateMany method. This method allows you to update all documents that match a specified query. Here is a basic example of how to use updateMany in both the MongoDB shell and with a MongoDB driver in a programming language like Node.js.
Using the MongoDB Shell
Connect to your MongoDB instance:
sh
mongo
Select the database:
javascript
use yourDatabaseName
Update multiple records:
javascript
db.yourCollectionName.updateMany(
{ query: { field: value } }, // Query to match documents
{ $set: { field: newValue } } // Update operation
)
Query (filter): Specifies the criteria for selecting documents to update.
Update Operation (update): Specifies the modifications to apply to the selected documents. The $set operator is commonly used to update specific fields.
Additional Options
upsert: If set to true, creates a new document if no documents match the query.
multi: If set to true, updates all documents that match the query. This is the default behavior for updateMany.