Docs HomeMongoDB Manual

find

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

In mongosh, this command can also be run through the db.collection.find() or db.collection.findOne() helper methods.mongosh中,此命令也可以通过db.collection.find()db.collection.findOne()助手方法运行。

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.助手方法对mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。如果不需要方便,或者需要额外的返回字段,请使用数据库命令。

Syntax语法

Changed in version 4.4.4.4版更改。MongoDB deprecates the oplogReplay option to the find command. MongoDB将oplogReplay选项弃用到find命令中。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.结果排序的排序规范。
projectiondocumentOptional.可选的。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 Query and Projection Operators operators: 视图上的操作不支持以下查询运算符和投影运算符
hintstring or documentOptional.可选的。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 integerOptional.可选的。The number of documents to return in the first batch. Defaults to 101. 第一批要返回的文档数。默认值为101A 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命令的batchSize为1不会关闭游标。
singleBatchbooleanOptional.可选的。Determines whether to close the cursor after the first batch. Defaults to false.确定是否在第一批之后关闭游标。默认为false
commentanyOptional.可选的。
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之前,注释只能是字符串。
maxTimeMSnon-negative integerOptional.可选的。
Specifies a time limit in milliseconds. 指定以毫秒为单位的时间限制。If you do not specify a value for maxTimeMS, operations will not time out. A value of 0 explicitly specifies the default unbounded behavior.如果不指定maxTimeMS的值,操作将不会超时。值0显式指定默认的无边界行为。
MongoDB terminates operations that exceed their allotted time limit using the same mechanism as db.killOp(). MongoDB使用与db.killOp()相同的机制终止超过指定时间限制的操作。MongoDB only terminates an operation at one of its designated interrupt points. 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. 确保操作不会无限期阻塞,而是确保在无法满足读取关注时操作返回错误。
readConcerndocumentOptional.可选的。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级别。
maxdocumentOptional.可选的。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,除非指定的filter_id字段上的相等条件{ _id: <value> }
mindocumentOptional.可选的。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. Default value is false. If returnKey is true and the find command does not use an index, the returned documents will be empty.如果为true,则仅返回结果文档中的索引键。默认值为false。如果returnKey为true,并且find命令不使用索引,则返回的文档将为空。
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. 如果在数据末尾,与tailable选项一起使用可以临时阻止游标上的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.可选的。用于重播复制集操作日志的内部命令。
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字段必须提供一个filter选项,使用以下比较运算符之一将ts文档字段与timestamp进行比较: For example, the following command replays documents from the data capped 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$eq筛选器的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分钟)后超时空闲游标。
allowPartialResultsbooleanOptional.可选的。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命令)返回部分结果,而不是错误。
If find (or subsequent getMore commands) returns partial results because the queried shard(s) aren't available, the find output includes a partialResultsReturned indicator field. 如果find(或后续的getMore命令)由于查询的分片不可用而返回部分结果,则 find输出包括一个partialResultsReturned指示符字段。If the queried shards are available for the initial find command, but one or more shards become unavailable for subsequent getMore commands, only the getMore commands that run while the shards aren't available include partialResultsReturned in their output. 如果查询到的分片可用于初始find命令,但一个或多个分片不可用于后续的getMore命令,则只有在分片不可用时运行的getMore命令在其输出中包含partialResultsReturned
collationdocumentOptional.可选的。
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选项具有以下语法:
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 booleanOptional.可选的。
Use this option to override allowDiskUseByDefault for a specific query. You can use this option to either: 使用此选项可以覆盖特定查询的allowDiskUseByDefault。您可以使用此选项执行以下操作之一:
  • Prohibit disk use on a system where disk use is allowed by default.在默认情况下允许使用磁盘的系统上禁止使用磁盘。
  • Allow disk use on a system where disk use is prohibited by default.允许在默认情况下禁止使用磁盘的系统上使用磁盘。
Starting in MongoDB 6.0, if allowDiskUseByDefault is set to true and the server requires more than 100 megabytes of memory for a pipeline execution stage, MongoDB automatically writes temporary files to disk unless the query specifies { allowDiskUse: false }.从MongoDB 6.0开始,如果allowDiskUseByDefault设置为true,并且服务器在管道执行阶段需要超过100兆字节的内存,MongoDB会自动将临时文件写入磁盘,除非查询指定{ allowDiskUse: false }
For details, see allowDiskUseByDefault.有关详细信息,请参阅allowDiskUseByDefault
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可以使用索引满足指定的sort或者阻塞排序所需的内存少于100兆字节,那么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版新增。
letdocumentOptional.可选的。
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. 例如:$$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描述
cursorContains 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选项This change makes $regex options more consistent with the use of $regex in the aggregate command and projection queries.此更改使$regex选项aggregate命令和投影查询中$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会话空闲超时

MongoDB drivers and mongosh associate all operations with a server session, with the exception of unacknowledged write operations. 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. When the MongoDB server closes the session, it also kills any in-progress operations and open cursors associated with the session. 如果会话空闲时间超过30分钟,MongoDB服务器会将该会话标记为已过期,并可能随时关闭该会话。当MongoDB服务器关闭会话时,它还会杀死任何正在进行的操作和打开与会话相关的游标。This includes cursors configured with noCursorTimeout() or a maxTimeMS() greater than 30 minutes.这包括配置为noCursorTimeout()maxTimeMS()大于30分钟的游标。

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.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项

Client Disconnection客户端断开连接

Starting in MongoDB 4.2, if the client that issued find disconnects before the operation completes, MongoDB marks find for termination using killOp.从MongoDB 4.2开始,如果发出find的客户端在操作完成之前断开连接,MongoDB会使用killOp标记find终止。

Stable API

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

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

Index Filters and Collations索引筛选器和排序规则

Starting in MongoDB 6.0, an index filter uses the collation previously set using the planCacheSetFilter command.从MongoDB 6.0开始,索引筛选器使用之前使用planCacheSetFilter命令设置的排序规则

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.该命令包含一个projection,只返回匹配文档中的以下字段:_idnameratingaddress字段。

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.提供了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" }
} )