在MongoDB中,您可以使用db.collection.updateMany()
方法更新集合中的多个文档。此方法更新集合中与给定过滤器匹配的所有文档。
updateMany()
是一个mongo shell方法,可以更新多个文档。此方法仅接受包含更新运算符表达式的文档。
- updateMany()方法可用于多文档事务中。
- 更新文档时,_id字段的值不变。
- 它还在文档中添加了新字段。
Syntax:
Parameters:
filter: First parameter of this method. It specifies the selection criteria for the update. The type of this parameter is document. If it contains empty document, i.e, {}, then this method will update all the documents of the collection with the update document.
update: Second parameter of this method. The type of this parameter is document or pipeline and it contains modification that will apply to the documents. It can be a update Document(only contain update operator expressions) or aggregation pipeline(only contain aggregation stages, i.e, $addFields
, $project
, $replaceRoot
).
Optional Parameters:
- upsert: The value of this parameter is either true or false. If the value of this parameter is true, then the method will update the documents that match the given condition or if any of the documents in the collection does not match the given filter, then this method will insert a new document(i.e., update Document) in the collection. The type of this parameter is a Boolean and the default value of this parameter is false.
- writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document.
- collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document.
- arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.
- hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled), matchedCount represents the number of matched documents, modifiedCount represents the number of modified documents, and upsertedId represents the _id of the upserted document.
更新所有文件
在MongoDB中,您可以使用db.collection.updateMany()
方法更新集合中的所有文档。
句法:
db.collection.updateMany(
,
,
{
upsert: ,
writeConcern: ,
collation: ,
arrayFilters: [ , ... ],
hint:
}
)
例子:
在以下示例中,我们正在使用:
db.collection.updateMany({}, {update})
更新所有文档:
在此示例中,我们将更新员工收款的所有文档。换句话说,我们正在更新所有员工的薪水。
Database: GeeksforGeeks
Collection: employee
Document: three documents that contain the details of the employees in the form of field-value pairs.
更新与过滤器匹配的多个文档:
在此示例中,我们将更新与给定过滤器匹配的雇员集合的多个文档。换句话说,我们正在更新分支机构为CSE的员工的薪水。
更新文档的多个字段:
在此示例中,我们将更新与雇员集合的给定过滤器匹配的文档的多个字段。