📜  updatemany mongodb (1)

📅  最后修改于: 2023-12-03 15:05:46.157000             🧑  作者: Mango

MongoDB Update Many

MongoDB is a document-oriented NoSQL database that provides a variety of powerful features. One of these features is the ability to update multiple documents at once using the updateMany() method.

Syntax

The syntax for the updateMany() method is as follows:

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>
   }
)

The updateMany() method takes three arguments:

  • <filter>: A query that selects which documents to update.
  • <update>: The modifications to apply to the selected documents.
  • <options>: Optional settings such as upsert, writeConcern, and collation.
Examples
Updating All Documents

To update all documents in a collection, you can use an empty filter and specify the modifications to apply in the update parameter:

db.collection.updateMany({}, { $set: { status: "ACTIVE" } })

This query sets the status field of all documents in the collection to "ACTIVE".

Updating Documents with a Specific Condition

To update only documents that match a specific condition, you can specify a filter in the first parameter:

db.collection.updateMany({ age: { $gt: 30 } }, { $set: { status: "ACTIVE" } })

This query sets the status field of all documents where the age field is greater than 30 to "ACTIVE".

Using Options

You can also specify optional settings such as upsert, writeConcern, and collation.

For example, to insert a new document if no matching document is found, you can set the upsert option to true:

db.collection.updateMany({ name: "John" }, { $set: { age: 40 } }, { upsert: true })

This query sets the age field of all documents with name "John" to 40. If no matching document is found, a new document will be inserted with name "John" and age set to 40.

Conclusion

The updateMany() method is a powerful tool for modifying multiple documents in a MongoDB collection. By specifying a filter and an update parameter, you can efficiently update many documents at once. Optional settings such as upsert, writeConcern, and collation provide further flexibility and control over the update process.