On this page本页内容
db.collection.findAndModify(document)¶mongo Shell Method
This page documents the 本页记录了mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. mongo shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。
Modifies and returns a single document. 修改并返回单个文档。By default, the returned document does not include the modifications made on the update. 默认情况下,返回的文档不包括对更新所做的修改。To return the document with the modifications made on the update, use the 要返回包含更新时所做修改的文档,请使用new option. new选项。The findAndModify() method is a shell helper around the findAndModify command.findAndModify()方法是findAndModify命令的shell助手。
The findAndModify() method has the following form:findAndModify()方法的形式如下:
The db.collection.findAndModify() method takes a document parameter with the following embedded document fields:db.collection.findAndModify()方法采用带有以下嵌入文档字段的文档参数:
query |
document |
|
|
document |
|
remove |
boolean | remove or the update field. remove或update字段。query field. query字段中指定的文档。true to remove the selected document . true可删除所选文档。false.false。 |
update |
document |
|
new |
boolean | true, returns the modified document rather than the original. true,则返回修改后的文档,而不是原始文档。db.collection.findAndModify() method ignores the new option for remove operations. db.collection.findAndModify()方法忽略remove操作的new选项。false.false。 |
fields |
document |
|
upsert |
boolean |
Defaults to |
bypassDocumentValidation |
boolean |
|
writeConcern |
document |
|
maxTimeMS |
integer | |
collation |
document |
|
arrayFilters |
array |
Note
Note
|
For remove operations, if the query matches a document, 对于删除操作,如果查询与文档匹配,findAndModify() returns the removed document. findAndModify()将返回删除的文档。If the query does not match a document to remove, 如果查询与要删除的文档不匹配,findAndModify() returns null.findAndModify()将返回null。
For update operations, 对于更新操作,findAndModify() returns one of the following:findAndModify()返回以下内容之一:
new parameter is not set or is false:new参数未设置或为false:null.null。new is true:new是true:upsert: true and no document matches the query;upsert:true且没有与查询匹配的文档,则插入的文档;null.null。fieldsLanguage Consistency
Starting in MongoDB 4.4, as part of making 从MongoDB 4.4开始,作为使find and findAndModify projection consistent with aggregation’s $project stage,find和findAndModify投影与聚合的$project阶段保持一致的一部分,
find and findAndModify projection can accept aggregation expressions and syntax.find和findAndModify投影可以接受聚合表达式和语法。Projection Restrictions for details.The fields option takes a document in the following form:fields选项采用以下格式的文档:
| Projection | |
|---|---|
<field>: <1 or true> |
|
<field>: <0 or false> |
|
"<field>.$": <1 or true> |
$ array projection operator, you can specify the projection to return the first element that match the query condition on the array field; e.g. "arrayField.$" : 1. $数组投影运算符,可以指定投影以返回与数组字段上的查询条件匹配的第一个元素;例如,"arrayField.$" : 1。 |
<field>: <array projection> |
$elemMatch, $slice, specifies the array element(s) to include, thereby excluding those elements that do not meet the expressions. $elemMatch,$slice,指定要包含的数组元素,从而排除那些不符合表达式的元素。 |
<field>: <aggregation expression> |
|
For fields in an embedded documents, you can specify the field using either:对于嵌入文档中的字段,可以使用以下任一方法指定字段:
"field.nestedfield": <value>{ field: { nestedfield: <value> } } (_id Field Projection¶The 默认情况下,_id field is included in the returned documents by default unless you explicitly specify _id: 0 in the projection to suppress the field._id字段包含在返回的文档中,除非在投影中明确指定_id:0以抑制该字段。
A projection cannot contain both include and exclude specifications, with the exception of the _id field:projection不能同时包含包含和排除规范,但_id字段除外:
_id field is the only field that you can explicitly exclude._id字段是唯一可以显式排除的字段。_id field is the only field that you can explicitly include; however, the _id field is included by default._id字段是唯一可以显式包括的字段;但是,默认情况下会包含_id字段。For more information on projection, see also:有关投影的更多信息,请参阅:
When 当findAndModify() includes the upsert:
true option and the query field(s) is not uniquely indexed, the method could insert a document multiple times in certain circumstances.findAndModify()包含upert:true选项且查询字段没有唯一索引时,该方法可能会在某些情况下多次插入文档。
In the following example, no document with the name 在以下示例中,不存在名为Andy exists, and multiple clients issue the following command:Andy的文档,多个客户端发出以下命令:
Then, if these clients’ 然后,如果这些客户机的findAndModify() methods finish the query phase before any command starts the modify phase, and there is no unique index on the name field, the commands may all perform an upsert, creating multiple duplicate documents.findAndModify()方法在任何命令开始modify阶段之前完成了query阶段,并且name字段上没有唯一索引,那么这些命令可能都会执行upsert,从而创建多个重复文档。
To prevent the creation of multiple duplicate documents with the same name, create a unique index on the 要防止创建多个同名重复文档,请在name field. name字段上创建唯一索引。With this unique index in place, the multiple methods will exhibit one of the following behaviors:有了这个独特的索引,多种方法将表现出以下行为之一:
findAndModify() successfully inserts a new document.findAndModify()成功插入了一个新文档。findAndModify() methods update the newly inserted document.findAndModify()方法更新新插入的文档。findAndModify() methods fail when they attempt to insert documents with the same name. findAndModify()方法在尝试插入同名文档时失败。name field, you can retry the method. name字段上的唯一索引约束冲突而失败,则可以重试该方法。When using 对分片集合使用findAndModify against a sharded collection, the query must contain an equality condition on shard key.findAndModify时,查询必须在分片键上包含相等条件。
Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 从4.4版开始,切分集合中的文档可能会缺少切分键字段。To target a document that is missing the shard key, you can use the 要将缺少切分键的文档作为目标,可以将null equality match in conjunction with another filter condition (such as on the _id field). null相等匹配与另一个筛选条件结合使用(例如在_id字段上)。For example:例如:
Starting in MongoDB 4.2, you can update a document’s shard key value unless the shard key field is the immutable 从MongoDB 4.2开始,可以更新文档的shard key值,除非shard key字段是不可变的_id field. _id字段。Before MongoDB 4.2, a document’s shard key field value is immutable.在MongoDB 4.2之前,文档的shard key字段值是不可变的。
Warning警告
Starting in version 4.4, documents in sharded collections can be missing the shard key fields. 从4.4版开始,分片集合中的文档可能会缺少分片键字段。Take precaution to avoid accidentally removing the shard key when changing a document’s shard key value.采取预防措施,以避免在更改文档的shard key值时意外删除shard key。
To modify the existing shard key value with 要使用db.collection.findAndModify():DBCollectionFindModify()修改现有分片键值,请执行以下操作:
mongos. mongos上运行。Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 从4.4版开始,切分集合中的文档可能会缺少切分键字段。To use 要使用db.collection.findAndModify() to set the document’s missing shard key:db.collection.findAndModify()设置文档缺少的碎片键,请执行以下操作:
mongos. mongos上运行。null.null,则必须在事务中或作为可重试写入运行。Tip
Since a missing key value is returned as part of a null equality match, to avoid updating a null-valued key, include additional query conditions (such as on the 由于缺少的键值是作为空相等匹配的一部分返回的,为了避免更新空值键值,请酌情包括其他查询条件(例如在_id field) as appropriate._id字段上)。
See also:
The db.collection.findAndModify() method adds support for the bypassDocumentValidation option, which lets you bypass document validation when inserting or updating documents in a collection with validation rules.db.collection.findAndModify()方法增加了对bypassDocumentValidation选项的支持,该选项允许在使用验证规则插入或更新集合中的文档时绕过文档验证。
update Methodupdate方法的比较¶When updating a document, 更新文档时,db.collection.findAndModify() and the update() method operate differently:db.collection.findAndModify()和update()方法的操作不同:
update() method with its multi option can modify more than one document.update()方法及其multi选项可以修改多个文档。db.collection.findAndModify(), you can specify a sort to provide some measure of control on which document to update.db.collection.findAndModify(),可以指定一种sort,以提供对要更新的文档的某种控制措施。
With the default behavior of the 使用update() method, you cannot specify which single document to update when multiple documents match.update()方法的默认行为,当多个文档匹配时,不能指定要更新的单个文档。
db.collection.findAndModify() returns the pre-modified version of the document. db.collection.findAndModify()返回文档的预修改版本。new option.new选项。
The update() method returns a WriteResult object that contains the status of the operation. update()方法返回一个WriteResult对象,该对象包含操作的状态。To return the updated document, use the 要返回更新的文档,请使用find() method. find()方法。However, other updates may have modified the document between your update and the document retrieval. 但是,其他更新可能在更新和文档检索之间修改了文档。Also, if the update modified only a single document but multiple documents matched, you will need to use additional logic to identify the updated document.此外,如果更新只修改了一个文档,但匹配了多个文档,则需要使用其他逻辑来标识更新后的文档。
When modifying a single document, both 修改单个文档时,db.collection.findAndModify() and the update() method atomically update the document. db.collection.findAndModify()和update()方法都会自动更新文档。See Atomicity and Transactions for more details about interactions and order of operations of these methods.有关这些方法的交互和操作顺序的更多详细信息,请参阅原子性和事务。
db.collection.findAndModify() can be used inside multi-document transactions.可以在多文档事务中使用。
Important重要的
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,而多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
Starting in MongoDB 4.4 with feature compatibility version (fcv) 从功能兼容版本(fcv)"4.4", you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction."4.4"的MongoDB 4.4开始,如果事务不是跨切分写入事务,则可以在多文档事务中创建集合和索引。
As such, for the feature compatibility version (fcv) is 因此,对于功能兼容性版本(fcv)为"4.4" or greater, db.collection.findAndModify() with upsert: true can be run against an existing collection or a non-existing collection. "4.4"或更高版本的情况,可以对现有集合或不存在的集合运行带有upsert:true的db.collection.findAndModify()。If run against a non-existing collection, the operation creates the collection.如果针对不存在的集合运行,该操作将创建该集合。
If the feature compatibility version (fcv) is 如果功能兼容版本(fcv)为"4.2" or less, the operation must be against an existing collection."4.2"或更低,则操作必须针对现有集合。
Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注点。To use write concern with transactions, see Transactions and Write Concern.要将写关注点用于事务,请参阅事务和写关注点。
In this section本节内容
The following method updates and returns an existing document in the people collection where the document matches the query criteria:以下方法更新并返回人员集合中与查询条件匹配的现有文档:
This method performs the following actions:此方法执行以下操作:
query finds a document in the people collection where the name field has the value Tom, the state field has the value active and the rating field has a value greater than 10.query会在people集合中找到一个文档,其中name字段的值为Tom,state字段的值为active,rating字段的值大于10。sort orders the results of the query in ascending order. sort按升序排列查询结果。query condition, the method will select for modification the first document as ordered by this sort.query条件,则该方法会选择按此sort排序的第一张单据进行修改。increments the value of the score field by 1.score字段的值增加1。To return the modified document, add the 要返回修改过的文档,请将new:true option to the method.new:true选项添加到方法中。
If no document matched the 如果没有与query condition, the method returns null.query条件匹配的文档,则该方法返回null。
The following method includes the 以下方法包括upsert: true option for the update operation to either update a matching document or, if no matching document exists, create a new document:upsert:true选项,用于update操作,以更新匹配的文档,或者如果不存在匹配的文档,则创建新文档:
If the method finds a matching document, the method performs an update.如果该方法找到匹配的文档,则该方法将执行更新。
If the method does not find a matching document, the method creates a new document. 如果该方法没有找到匹配的文档,则该方法将创建一个新文档。Because the method included the 因为该方法包含排序选项,所以它返回一个空文档sort option, it returns an empty document { } as the original (pre-modification) document:{ },作为原始(修改前)文档:
If the method did not include a 如果该方法不包含sort option, the method returns null.sort选项,则该方法返回null。
The following method includes both the 以下方法包括upsert: true option and the new:true option. upsert:true选项和new:true选项。The method either updates a matching document and returns the updated document or, if no matching document exists, inserts a document and returns the newly inserted document in the 该方法要么更新匹配文档并返回更新后的文档,要么在不存在匹配文档的情况下插入文档并在value field.value字段中返回新插入的文档。
In the following example, no document in the 在以下示例中,people collection matches the query condition:people集合中没有与查询条件匹配的文档:
The method returns the newly inserted document:该方法返回新插入的文档:
By including a 通过在sort specification on the rating field, the following example removes from the people collection a single document with the state value of active and the lowest rating among the matching documents:rating字段中包含sort规范,以下示例将从people集合中删除state值active且rating最低的单个文档:
The method returns the deleted document:该方法返回已删除的文档:
New in version 3.4.版本3.4中的新功能。
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。
A collection myColl has the following documents:myColl集合包含以下文档:
The following operation includes the collation option:以下操作包括排序规则选项:
The operation returns the following document:该操作将返回以下文档:
arrayFilters for an Array Update OperationsarrayFilters¶Note
arrayFilters is not available for updates that use an aggregation pipeline.不适用于使用聚合管道的更新。
New in version 3.6.版本3.6中的新功能。
Starting in MongoDB 3.6, when updating an array field, you can specify 从MongoDB 3.6开始,在更新数组字段时,可以指定确定要更新哪些数组元素的arrayFilters that determine which array elements to update.arrayFilters。
arrayFilters CriteriaarrayFilters条件¶Note
arrayFilters is not available for updates that use an aggregation pipeline.arrayFilters不适用于使用聚合管道的更新。
Create a collection 创建一个包含以下文档的集合students with the following documents:students:
To modify all elements that are greater than or equal to 要修改100 in the grades array, use the filtered positional operator $[<identifier>] with the arrayFilters option in the db.collection.findAndModify method:grades数组中大于或等于100的所有元素,请在db.collection.findAndModify方法中使用筛选的位置运算符$[<identifier>]和arrayFilters选项:
The operation updates the 该操作将更新单个文档的grades field for a single document, and after the operation, the collection has the following documents:grades字段,操作完成后,集合将包含以下文档:
Note
arrayFilters is not available for updates that use an aggregation pipeline.arrayFilters不适用于使用聚合管道的更新。
Create a collection 使用以下文档创建students2 with the following documents:students2集合:
The following operation finds a document where the 以下操作将查找_id field equals 1 and uses the filtered positional operator $[<identifier>] with the arrayFilters to modify the mean for all elements in the grades array where the grade is greater than or equal to 85._id字段等于1的文档,并使用筛选后的位置运算符$[<identifier>]和arrayFilters来修改grades数组中等级大于或等于85的所有元素的平均值。
The operation updates the 该操作将更新单个文档的grades field for a single document, and after the operation, the collection has the following documents:grades字段,操作完成后,集合将包含以下文档:
Starting in MongoDB 4.2, 从MongoDB 4.2开始,db.collection.findAndModify() can accept an aggregation pipeline for the update. db.collection.findAndModify()可以接受更新的聚合管道。The pipeline can consist of the following stages:管道可包括以下阶段:
$addFields$set$project$unset$replaceRoot$replaceWithUsing the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).使用聚合管道可以实现更具表现力的update语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。
For example, create a collection 例如,使用以下文档创建students2 with the following documents:students2集合:
The following operation finds a document where the 以下操作将查找_id field equals 1 and uses an aggregation pipeline to calculate a new field total from the grades field:_id字段等于1的文档,并使用聚合管道从grades字段计算新字段grades:
Note
The 管道中使用的$set used in the pipeline refers to the aggregation stage $set and not the update operator $set.$set指的是聚合阶段$set,而不是更新运算符$set。
The operation returns the updated document:该操作将返回更新后的文档: