find

On this page本页内容

Definition定义

find

Executes a query and returns the first batch of results and the cursor id, from which the client can construct a cursor.执行查询并返回第一批结果和游标id,客户端可以从中构造游标。

Tip提示

Rather than run the find command directly, you can use the db.collection.find() helper provided in mongosh or the equivalent helper in the drivers.您可以使用mongosh中提供的db.collection.find()助手或驱动程序中的等效助手,而不是直接运行find命令。

Syntax语法

Changed in version 4.4.在版本4.4中更改

MongoDB deprecates the oplogReplay option to the find command. MongoDB不推荐find命令的oplogReplay选项。The optimization enabled by this flag in previous versions now happens automatically for eligible queries on the oplog. 在以前的版本中,此标志启用的优化现在会自动用于oplog上符合条件的查询。Therefore, you don't need to specify this flag. 因此,您不需要指定此标志。If specified, the server accepts the flag for backwards compatibility, but the flag has no effect.如果指定,服务器将接受向后兼容性标志,但该标志无效。

The find command has the following syntax:find命令具有以下语法:

Changed in version 5.0.在版本5.0中更改

db.runCommand(
   {
      "find": <string>,
      "filter": <document>,
      "sort": <document>,
      "projection": <document>,
      "hint": <document or string>,
      "skip": <int>,
      "limit": <int>,
      "batchSize": <int>,
      "singleBatch": <bool>,
      "comment": <any>,
      "maxTimeMS": <int>,
      "readConcern": <document>,
      "max": <document>,
      "min": <document>,
      "returnKey": <bool>,
      "showRecordId": <bool>,
      "tailable": <bool>,
      "oplogReplay": <bool>,
      "noCursorTimeout": <bool>,
      "awaitData": <bool>,
      "allowPartialResults": <bool>,
      "collation": <document>,
      "allowDiskUse" : <bool>,
      "let": <document> // Added in MongoDB 5.0
   }
)

Command Fields命令字段

The command accepts the following fields:该命令接受以下字段:

Field字段Type类型Description描述
findstringThe name of the collection or view to query.要查询的集合或视图的名称。
filterdocumentOptional. 可选。The query predicate. 查询谓词。If unspecified, then all documents in the collection will match the predicate. 如果未指定,则集合中的所有文档都将与谓词匹配。

sort

documentOptional. 可选。The sort specification for the ordering of the results.结果排序的排序规范。
projectiondocument

Optional. 可选。The projection specification to determine which fields to include in the returned documents. 投影规范,用于确定在返回的文档中包含哪些字段。See Projection and Projection Operators.请参见投影投影运算符

find() operations on views do not support the following projection operators:视图上的find()操作不支持以下投影运算符:

hintstring or document

Optional. 可选。Index specification. 索引规格。Specify either the index name as a string or the index key pattern. 将索引名称指定为字符串或索引键模式。If specified, then the query system will only consider plans using the hinted index.如果指定,查询系统将只考虑使用提示索引的计划。

Starting in MongoDB 4.2, with the following exception, hint is required if the command includes the min and/or max fields; hint is not required with min and/or max if the filter is an equality condition on the _id field { _id: <value> }.从MongoDB 4.2开始,除了以下例外,如果命令包含min和/或max字段,则需要hint;如果filter_id字段{ _id: <value> }上的相等条件,则min和/或max不需要hint

skipPositive integerOptional. 可选。Number of documents to skip. Defaults to 0.要跳过的文档数。默认为0。
limitNon-negative integerOptional. 可选。The maximum number of documents to return. If unspecified, then defaults to no limit. 要返回的最大文档数。如果未指定,则默认为无限制。A limit of 0 is equivalent to setting no limit. 限制为0等于不设置限制。
batchSizenon-negative integer

Optional. 可选。The number of documents to return in the first batch. 第一批中要返回的文档数。Defaults to 101. 默认为101。A batchSize of 0 means that the cursor will be established, but no documents will be returned in the first batch.batchSize为0表示将建立游标,但第一批中不会返回任何文档。

Unlike the previous wire protocol version, a batchSize of 1 for the find command does not close the cursor.与以前的有线协议版本不同,find命令的batchSize1不会关闭游标。

singleBatchbooleanOptional. 可选。Determines whether to close the cursor after the first batch. 确定是否在第一批之后关闭游标。Defaults to false. 默认为false
commentany

Optional. 可选。A user-provided comment to attach to this command. 用户提供了附加到此命令的注释。Once set, this comment appears alongside records of this command in the following locations:设置后,此注释将与此命令的记录一起显示在以下位置:

A comment can be any valid BSON type(string, integer, object, array, etc).注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。

Note注意

Any comment set on a find command is inherited by any subsequent getMore commands run on the find cursor.find命令上的任何注释集都会被find游标上运行的任何后续getMore命令继承。

Changed in version 4.4..在版本4.4.中更改

Prior to 4.4, comments could only be strings.在4.4之前,注释只能是字符串。

maxTimeMSpositive integer

Optional. 可选。The cumulative time limit in milliseconds for processing operations on the cursor. 处理游标操作的累积时间限制(毫秒)。MongoDB aborts the operation at the earliest following interrupt point.MongoDB在下一个中断点最早中止操作。

Tip提示

When specifying linearizable read concern, always use maxTimeMS in case a majority of data bearing members are unavailable. 指定linearizable读取关注点时,如果大多数数据承载成员不可用,请始终使用maxTimeMSmaxTimeMS ensures that the operation does not block indefinitely and instead ensures that the operation returns an error if the read concern cannot be fulfilled.确保操作不会无限期阻塞,而是确保如果无法满足读取问题,则操作返回错误。

readConcerndocument

Optional. 可选。Specifies the read concern.指定读取关注点

Starting in MongoDB 3.6, the readConcern option has the following syntax: 从MongoDB 3.6开始,readConcern选项具有以下语法:readConcern: { level: <value> }

Possible read concern levels are:可能的读取关注级别为:

  • "local". This is the default read concern level for read operations against the primary and secondaries.这是针对主和辅助的读取操作的默认读取关注级别。
  • "available". Available for read operations against the primary and secondaries. 可用于对主要和次要磁盘执行读取操作。"available" behaves the same as "local" against the primary and non-sharded secondaries. "available""local"在主要和非分片次要磁盘上的行为相同。The query returns the instance's most recent data.查询返回实例的最新数据。
  • "majority". Available for replica sets that use WiredTiger storage engine.适用于使用WiredTiger存储引擎的副本集。
  • "linearizable". Available for read operations on the primary only.仅可用于primary上的读取操作。

For more formation on the read concern levels, see Read Concern Levels.有关读取关注级别的更多信息,请参阅读取关注级别

The getMore command uses the readConcern level specified in the originating find command.getMore命令使用原始find命令中指定的readConcern级别。

maxdocument

Optional. 可选。The exclusive upper bound for a specific index. 特定索引的排除上限。See cursor.max() for details.有关详细信息,请参阅cursor.max()

Starting in MongoDB 4.2, to use the max field, the command must also use hint unless the specified filter is an equality condition on the _id field { _id: <value> }.从MongoDB 4.2开始,要使用max字段,该命令还必须使用hint,除非指定的筛选器是_id字段{ _id: <value> }上的相等条件。

mindocument

Optional. 可选。The inclusive lower bound for a specific index. 特定索引的包含下限。See cursor.min() for details.有关详细信息,请参阅cursor.min()

Starting in MongoDB 4.2, to use the min field, the command must also use hint unless the specified filter is an equality condition on the _id field { _id: <value> }.从MongoDB 4.2开始,要使用min字段,命令还必须使用hint,除非指定的filter_id字段{ _id: <value> }上的相等条件。

returnKeybooleanOptional. 可选。If true, returns only the index keys in the resulting documents. 如果为true,则只返回结果文档中的索引键。Default value is false. 默认值为falseIf returnKey is true and the find command does not use an index, the returned documents will be empty. 如果returnKeytruefind命令不使用索引,则返回的文档将为空。
showRecordIdbooleanOptional. 可选。Determines whether to return the record identifier for each document. 确定是否返回每个文档的记录标识符。If true, adds a field $recordId to the returned documents. 如果为true,则在返回的文档中添加字段$recordId
tailablebooleanOptional. 可选。Returns a tailable cursor for a capped collections.返回带帽集合的可剪裁游标
awaitDatabooleanOptional. 可选。Use in conjunction with the tailable option to block a getMore command on the cursor temporarily if at the end of data rather than returning no data. getMore选项一起使用,如果在数据结束时而不是返回任何数据,则可以暂时阻止游标上的getMore命令。After a timeout period, find returns as normal. 超时后,find返回正常。
oplogReplayboolean

Deprecated since version 4.4.自4.4版以来已弃用

Optional. 可选。An internal command for replaying a replica set's oplog.用于重播副本集oplog的内部命令。

To use oplogReplay, the find field must provide a filter option comparing the ts document field to a timestamp using one of the following comparison operators:要使用oplogReplayfind字段必须提供一个筛选器选项,使用以下比较运算符之一将ts文档字段与timestamp进行比较:

For example, the following command replays documents from the datacapped collection with a timestamp later than or equal to January 1st, 2018 UTC:例如,以下命令以晚于或等于2018年1月1日UTC的时间戳重放data封顶集合中的文档:

{ find: "data",
  oplogReplay: true,
  filter: { ts: { $gte: new Timestamp(1514764800, 0) } } }
Note注意
Deprecated已弃用

Changed in version 4.4.在版本4.4中更改

Starting in MongoDB 4.4, the oplogReplay field is deprecated. 从MongoDB 4.4开始,oplogReplay字段已弃用。find fields that use the $gte, $gt, or $eq filter predicated on the ts field will automatically utilize the storage format of the replica set's oplog to execute the command more efficiently. 使用以ts字段为谓词的$gte$gt$eqfilter的find字段将自动利用副本集oplog的存储格式来更高效地执行命令。If specified, the server accepts the oplogReplay flag for backwards compatibility, but the flag has no effect.如果指定,服务器将接受oplogReplay标志以实现向后兼容性,但该标志无效。

noCursorTimeoutbooleanOptional. 可选。Prevents the server from timing out idle cursors after an inactivity period (10 minutes). 防止服务器在一段非活动时间(10分钟)后使空闲游标超时。
allowPartialResultsboolean

Optional. 可选。For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable.对于针对分片集合的查询,如果一个或多个查询的分片不可用,则允许命令(或后续的getMore命令)返回部分结果,而不是错误。

Starting in MongoDB 4.4, if find (or subsequent getMore commands) returns partial results due to the unavailability of the queried shard(s), the output includes a partialResultsReturned indicator field.从MongoDB 4.4开始,如果find(或随后的getMore命令)由于查询的分片不可用而返回部分结果,则输出包括partialResultsReturned指示符字段。

If the queried shards are initially available for the find command but one or more shards become unavailable in subsequent getMore commands, only the getMore commands run when a queried shard or shards are unavailable include the partialResultsReturned flag in the output.如果查询的分片最初可用于find命令,但一个或多个分片在随后的getMore命令中不可用,则只有在查询的分片不可用时运行的getMore命令才会在输出中包含partialResultsReturned标志。

collationdocument

Optional.可选。

Specifies the collation to use for the operation.指定用于操作的排序规则

collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如字母和重音标记的规则。

The collation option has the following syntax:排序规则选项具有以下语法:

collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

When specifying collation, the locale field is mandatory; all other collation fields are optional. 指定排序规则时,locale字段是必填的;所有其他排序字段都是可选的。For descriptions of the fields, see Collation Document.有关字段的说明,请参阅排序规则文档

If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.如果未指定排序规则,但集合具有默认排序规则(请参见db.createCollection()),则操作将使用为集合指定的排序规则。

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.如果没有为集合或操作指定排序规则,MongoDB将使用以前版本中使用的简单二进制比较进行字符串比较。

You cannot specify multiple collations for an operation. 不能为一个操作指定多个排序规则。For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能将一种排序规则用于查找,另一种用于排序。

allowDiskUse

boolean

Optional.可选。

Use allowDiskUse to allow MongoDB to use temporary files on disk to store data exceeding the 100 megabyte memory limit while processing a non-indexed ("blocking") sort operation. 使用allowDiskUse允许MongoDB在处理非索引(“阻塞”)排序操作时使用磁盘上的临时文件来存储超过100 MB内存限制的数据。If MongoDB requires using more than 100 megabytes of memory for a blocking sort operation, MongoDB returns an error unless the query specifies allowDiskUse. 如果MongoDB需要使用超过100 MB的内存进行阻塞排序操作,则MongoDB将返回一个错误,除非查询指定allowDiskUseSee Sort and Index Use for more information on blocking sort operations.有关阻塞排序操作的更多信息,请参阅排序和索引使用

allowDiskUse has no effect if MongoDB can satisfy the specified sort using an index, or if the blocking sort requires less than 100 megabytes of memory.如果MongoDB可以使用索引满足指定的排序,或者如果分块排序需要的内存小于100 MB,allowDiskUse将无效。

For more complete documentation on allowDiskUse, see cursor.allowDiskUse().有关allowDiskUse的更多完整文档,请参阅cursor.allowDiskUse()

For more information on memory restrictions for large blocking sorts, see Sort and Index Use.有关大型块排序的内存限制的更多信息,请参阅排序和索引使用

New in version 4.4.在版本4.4中新增

letdocument

Optional.可选。

Specifies a document with a list of variables. 指定具有变量列表的文档。This allows you to improve command readability by separating the variables from the query text.这允许您通过将变量与查询文本分离来提高命令的可读性。

The document syntax is:文档语法为:

{ <variable_name_1>: <expression_1>,
  ...,
  <variable_name_n>: <expression_n> }

The variable is set to the value returned by the expression, and cannot be changed afterwards.变量被设置为表达式返回的值,之后无法更改。

To access the value of a variable in the command, use the double dollar sign prefix ($$) together with your variable name in the form $$<variable_name>. 要在命令中访问变量的值,请使用双美元符号前缀($$)和变量名,格式为$$<variable_name>For example: 例如:$$targetTotal.

Note注意

To use a variable to filter results, you must access the variable within the $expr operator.要使用变量筛选结果,必须在$expr运算符中访问该变量。

For a complete example using let and variables, see Use Variables in let.有关使用let和变量的完整示例,请参阅let中使用变量

New in version 5.0.在版本5.0中新增

Output输出

The command returns a document that contains the cursor information, including the cursor id and the first batch of documents. 该命令返回包含游标信息的文档,包括游标id和第一批文档。For example, the following document is returned when run against a sharded collection:例如,当对分片集合运行时,将返回以下文档:

{
   "cursor" : {
      "firstBatch" : [
         {
            "_id" : ObjectId("5e8e2ca217b5324fa9847435"),
            "zipcode" : "20001",
            "x" : 1
         },
         {
            "_id" : ObjectId("5e8e2ca517b5324fa9847436"),
            "zipcode" : "30001",
            "x" : 1
         }
      ],
      "partialResultsReturned" : true, // Starting in version 4.4
      "id" : NumberLong("668860441858272439"),
      "ns" : "test.contacts"
   },
   "ok" : 1,
   "operationTime" : Timestamp(1586380205, 1),
   "$clusterTime" : {
      "clusterTime" : Timestamp(1586380225, 2),
      "signature" : {
         "hash" : BinData(0,"aI/jWsUVUSkMw8id+A+AVVTQh9Y="),
         "keyId" : NumberLong("6813364731999420435")
      }
   }
}
Field字段Description描述
cursor

Contains the cursor information, including the cursor id and the firstBatch of documents.包含游标信息,包括游标id和文档的firstBatch

Starting in 4.4, if the operation against a sharded collection returns partial results due to the unavailability of the queried shard(s), the cursor document includes a partialResultsReturned field. 从4.4开始,如果由于查询的分片不可用,对分片集合的操作返回部分结果,则cursor文档包含partialResultsReturned字段。To return partial results, rather than error, due to the unavailability of the queried shard(s), the find command must run with allowPartialResults set to true. 由于查询的分片不可用,要返回部分结果而不是错误,find命令必须在allowPartialResults设置为true的情况下运行。See allowPartialResults.请参见allowPartialResults

If the queried shards are initially available for the find command but one or more shards become unavailable in subsequent getMore commands, only the getMore commands run when a queried shard or shards are unavailable include the partialResultsReturned flag in the output.如果查询的分片最初可用于find命令,但一个或多个分片在随后的getMore命令中不可用,则只有在查询的分片不可用时运行的getMore命令才会在输出中包含partialResultsReturned标志。

"ok"Indicates whether the command has succeeded (1) or failed (0). 指示命令是成功(1)还是失败(0)。

In addition to the aforementioned find-specific fields, the db.runCommand() includes the following information for replica sets and sharded clusters:除了前面提到的find特定字段之外,db.runCommand()还包括以下副本集和分片集群的信息:

  • $clusterTime
  • operationTime

See db.runCommand() Results for details.有关详细信息,请参阅db.runCommand()结果

Behavior行为

$regex Find Queries No Longer Ignore Invalid Regex查找查询不再忽略无效的Regex

Starting in MongoDB 5.1, invalid $regex options options are no longer ignored. 从MongoDB 5.1开始,不再忽略无效的$regex options选项。This change makes $regex options more consistent with the use of $regex in the aggregate command and projection queries.此更改使$regex optionsaggregate命令和projection查询中使用$regex更加一致。

Sessions会话

New in version 4.0.在版本4.0中新增

For cursors created inside a session, you cannot call getMore outside the session.对于在会话内创建的游标,不能在会话外调用getMore

Similarly, for cursors created outside of a session, you cannot call getMore inside a session.同样,对于在会话外部创建的游标,不能在会话内部调用getMore

Session Idle Timeout会话空闲超时

Starting in MongoDB 3.6, MongoDB drivers and mongosh associate all operations with a server session, with the exception of unacknowledged write operations. 从MongoDB 3.6开始,MongoDB驱动程序和mongosh将所有操作与服务器会话相关联,但未确认的写入操作除外。For operations not explicitly associated with a session (i.e. using Mongo.startSession()), MongoDB drivers and mongosh create an implicit session and associate it with the operation.对于与会话没有显式关联的操作(即使用Mongo.startSession()),MongoDB驱动程序和mongosh创建一个隐式会话并将其与操作关联。

If a session is idle for longer than 30 minutes, the MongoDB server marks that session as expired and may close it at any time. 如果会话空闲时间超过30分钟,MongoDB服务器会将该会话标记为过期,并可以随时关闭。When the MongoDB server closes the session, it also kills any in-progress operations and open cursors associated with the session. 当MongoDB服务器关闭会话时,它也会终止任何正在进行的操作和与会话关联的打开游标。This includes cursors configured with noCursorTimeout() or a maxTimeMS() greater than 30 minutes.这包括使用noCursorTimeout()或大于30分钟的maxTimeMS()配置的游标。

For operations that return a cursor, if the cursor may be idle for longer than 30 minutes, issue the operation within an explicit session using Mongo.startSession() and periodically refresh the session using the refreshSessions command. 对于返回游标的操作,如果游标空闲时间可能超过30分钟,请使用Mongo.startSession()在显式会话中发出操作,并使用refreshSessions命令定期刷新会话。See Session Idle Timeout for more information.有关详细信息,请参阅会话空闲超时

Transactions事务

find can be used inside multi-document transactions.可以在多文档事务中使用。

  • For cursors created outside of a transaction, you cannot call getMore inside the transaction.对于在事务外部创建的游标,不能在事务内部调用getMore
  • For cursors created in a transaction, you cannot call getMore outside the transaction.对于在事务中创建的游标,不能在事务外部调用getMore
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大小限制),请参阅生产注意事项

Client Disconnection客户端断开连接

Starting in MongoDB 4.2, if the client that issued the find disconnects before the operation completes, MongoDB marks the find for termination (i.e. killOp on the operation).从MongoDB 4.2开始,如果发出find的客户端在操作完成之前断开连接,MongoDB将find标记为终止(即操作上的killOp)。

Stable API稳定的API

When using Stable API V1, the following find command fields are not supported:使用稳定API V1时,不支持以下find命令字段:

  • awaitData
  • max
  • min
  • noCursorTimeout
  • oplogReplay
  • returnKey
  • showRecordId
  • tailable

Examples示例

Specify a Sort and Limit指定排序和限制

The following command runs the find command filtering on the rating field and the cuisine field. 以下命令在rating字段和cuisine字段上运行find命令筛选。The command includes a projection to only return the following fields in the matching documents: _id, name, rating, and address fields.该命令包括一个投影,只返回匹配文档中的以下字段:_idnamenameaddress字段。

The command sorts the documents in the result set by the name field and limits the result set to 5 documents.该命令按name字段对结果集中的文档进行排序,并将结果集限制为5个文档。

db.runCommand(
   {
     find: "restaurants",
     filter: { rating: { $gte: 9 }, cuisine: "italian" },
     projection: { name: 1, rating: 1, address: 1 },
     sort: { name: 1 },
     limit: 5
   }
)

Override Default Read Concern覆盖默认读取问题

To override the default read concern level of "local", use the readConcern option.要覆盖"local"的默认读取关注级别,请使用readConcern选项。

The following operation on a replica set specifies a read concern of "majority" to read the most recent copy of the data confirmed as having been written to a majority of the nodes.以下对副本集的操作指定了"majority"读取问题,以读取确认已写入大多数节点的数据的最新副本。

db.runCommand(
   {
     find: "restaurants",
     filter: { rating: { $lt: 5 } },
     readConcern: { level: "majority" }
   }
)

Regardless of the read concern level, the most recent data on a node may not reflect the most recent version of the data in the system.无论读取关注级别如何,节点上的最新数据可能不会反映系统中数据的最新版本。

The getMore command uses the readConcern level specified in the originating find command.getMore命令使用原始find命令中指定的readConcern级别。

A readConcern can be specified for the mongosh method db.collection.find() using the cursor.readConcern() method:可以使用cursor.readConcern()方法为mongosh方法db.collection.find()指定readConcern

db.restaurants.find( { rating: { $lt: 5 } } ).readConcern("majority")

For more information on available read concerns, see Read Concern.有关可用读取关注的更多信息,请参阅读取关注

Specify Collation指定排序规则

collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如字母和重音标记的规则。

The following operation runs the find command with the collation specified:以下操作使用指定的排序规则运行find命令:

db.runCommand(
   {
     find: "myColl",
     filter: { category: "cafe", status: "a" },
     sort: { category: 1 },
     collation: { locale: "fr", strength: 1 }
   }
)

mongosh provides the cursor.collation() to specify collation for a db.collection.find() operation.mongosh提供了cursor.collation()来指定db.collection.find()操作的排序规则

Use Variables in letlet中使用变量

New in version 5.0.在版本5.0中新增

To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他位置访问的变量,请使用let选项。

Note注意

To filter results using a variable, you must access the variable within the $expr operator.要使用变量筛选结果,必须在$expr运算符中访问该变量。

Create a collection cakeFlavors:创建集合cakeFlavors

db.cakeFlavors.insertMany( [
   { _id: 1, flavor: "chocolate" },
   { _id: 2, flavor: "strawberry" },
   { _id: 3, flavor: "cherry" }
] )

The following example defines a targetFlavor variable in let and uses the variable to retrieve the chocolate cake flavor:下面的示例在let中定义了一个targetFlavor变量,并使用该变量检索巧克力蛋糕口味:

db.cakeFlavors.runCommand( {
   find: db.cakeFlavors.getName(),
   filter: { $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
   let : { targetFlavor: "chocolate" }
} )
←  deletefindAndModify →