Database Manual / Reference / Query Language / CRUD Commands

find (database command)(数据库命令)

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. 助手方法对mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。In cases where the convenience is not needed or the additional return fields are required, use the database command.如果不需要便利性或需要额外的返回字段,请使用database命令。

Compatibility兼容性

This command is available in deployments hosted in the following environments:此命令在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Important

This command has limited support in M0 and Flex clusters. For more information, see Unsupported Commands.此命令在M0和Flex集群中的支持有限。有关详细信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

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
}
)

Note

Since MongoDB 4.4, the find command ignores the oplogReplay flag. 从MongoDB 4.4开始,find命令忽略oplogReplay标志。If the oplogReplay flag is set, the server accepts it for backwards compatibility, but has no effect.如果设置了oplogReplay标志,服务器会接受它以实现向后兼容性,但不会产生任何影响。

Command Fields命令字段

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

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

sort

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

Optional. The projection specification to determine which fields to include in the returned documents.可选。用于确定返回文档中应包含哪些字段的投影规范

find() operations on views do not support the following find command projection operators:视图上的find()操作不支持以下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.可选。指标规范。将索引名称指定为字符串或索引键模式。如果指定,则查询系统将仅考虑使用提示索引的计划。

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> }.除了以下例外情况,如果命令包含min和/或max字段,则需要hint(提示);如filter_id字段{ _id: <value> }上的相等条件,则min和/或max不需要hint

skipPositive integer的正整数Optional. Number of documents to skip. Defaults to 0.可选。要跳过的文档数。默认为0。
limitNon-negative integer非负整数Optional. 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 maximum number of documents that can be returned in each batch of a query result. 可选。每批查询结果中可以返回的最大文档数。By default, the find command has an initial batchSize of the lesser of 101 documents or 16 mebibytes (MiB) worth of documents. 默认情况下,find命令的初始batchSize(批大小)为101个文档或16兆字节(MiB)的文档中的较小值。Subsequent batches have a maximum size of 16 MiB. 后续批次的最大容量为16 MiB。This option can enforce a smaller limit than 16 MiB, but not a larger one. When set, the batchSize is the lesser of batchSize documents or 16 MiB worth of documents.此选项可以强制执行小于16 MiB的限制,但不能强制执行更大的限制。设置后,batchSizebatchSize文档或价值16 MiB的文档中的较小值。

A batchSize of 0 means that the cursor is established, but no documents are returned in the first batch.batchSize0表示游标已建立,但第一批中没有返回文档。

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

singleBatch

boolean布尔值Optional.可选。 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类型(字符串、整数、对象、数组等)。

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

maxTimeMSnon-negative integer非负整数

Optional.可选。

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仅在其指定的中断点之一终止操作。

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

readConcerndocument文档

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

The readConcern option has the following syntax: 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. The query returns the instance's most recent data.对primary和非分片secondary的行为与"local"相同。查询返回实例的最新数据。
  • "majority". Available for replica sets that use WiredTiger storage engine.。适用于使用WiredTiger存储引擎的副本集。
  • "linearizable". Available for read operations on the primary only.。仅适用于primary上的读取操作。
  • "snapshot". Available for multi-document transactions and certain read operations outside of multi-document transactions.。可用于多文档事务和多文档事务之外的某些读取操作。

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()

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> }.要使用max字段,命令还必须使用hint,除非指定的filter(筛选器)是_id字段{ _id: <value> }的相等条件。

mindocument文档

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

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> }.要使用min字段,命令还必须使用hint,除非指定的filter_id字段{ _id: <value> }的相等条件。

returnKeyboolean布尔值Optional.可选。 If true, returns only the index keys in the resulting documents. Default value is false. 如果为true,则仅返回结果文档中的索引键。默认值为falseIf returnKey is true and the find command does not use an index, the returned documents will be empty.如果returnKeytrue并且find命令不使用索引,则返回的文档将为空。
showRecordIdboolean布尔值Optional.可选。 Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents.确定是否返回每个文档的记录标识符。如果为true,则向返回的文档添加字段$recordId
tailableboolean布尔值Optional.可选。 Returns a tailable cursor for a capped collections.返回带上限集合的可尾随游标
awaitDataboolean布尔值Optional.可选。 Use in conjunction with the tailable option to block a getMore command on the cursor temporarily at the end of data rather than returning no data. 与可尾随选项结合使用,在数据末尾临时阻止游标上的getMore命令,而不是不返回任何数据。After a timeout period, find returns as normal.超时后,find将正常返回。
noCursorTimeoutboolean布尔值Optional.可选。 Prevents the server from timing out non-session idle cursors after an inactivity period of 30 minutes. Ignored for cursors that are part of a session. 防止服务器在30分钟的不活动期后超时非会话空闲游标。对于会话中的游标,忽略此选项。For more information, refer to Session Idle Timeout.有关更多信息,请参阅会话空闲超时
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命令)返回部分结果,而不是错误。

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

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. For descriptions of the fields, see Collation Document.指定排序规则时,locale字段是必填的;所有其他排序字段都是可选的。有关字段的描述,请参阅排序规则文档

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 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 in-memory sort requires less than 100 megabytes of memory.如果MongoDB可以使用索引满足指定的排序,或者如果内存中的排序需要少于100兆字节的内存,则没有效果。

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

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

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>. For example: $$targetTotal.要在命令中访问变量的值,请使用双美元符号前缀($$)和变量名,格式为$$<variable_name>。例如:$$targetTotal

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. For example, the command returns the following document when run against a sharded collection:该命令返回一个包含游标信息的文档,包括游标ID和第一批文档。例如,当对分片集合运行时,该命令返回以下文档:

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

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

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. 如果对分片集合的操作由于查询的分片不可用而返回部分结果,则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()结果

If you don't require a raw command response, use the db.collection.find() or db.collection.findOne() helper methods.如果不需要原始命令响应,请使用db.collection.find()db.collection.findOne()辅助方法。

Behavior行为

$regex Find Queries No Longer Ignore Invalid Regex查找查询不再忽略无效正则表达式

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

Sessions会话

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()或大于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 distributed transactions.find可以在分布式事务中使用。

  • 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, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed 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 distributed transactions.对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续是您的数据和用例的最佳选择。也就是说,对于许多场景,适当地对数据进行建模将最大限度地减少对分布式事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),另请参阅生产注意事项

Client Disconnection客户端断开连接

If the client that issued find disconnects before the operation completes, MongoDB marks find for termination using killOp.如果发出find命令的客户端在操作完成之前断开连接,MongoDB将使用killOp标记find终止。

Stable API稳定API

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

  • awaitData
  • max
  • min
  • noCursorTimeout
  • 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命令设置的排序规则

Starting in MongoDB 8.0, use query settings instead of adding index filters. Index filters are deprecated starting in MongoDB 8.0.从MongoDB 8.0开始,使用查询设置,而不是添加索引筛选器。索引筛选器从MongoDB 8.0开始就被弃用。

Query settings have more functionality than index filters. Also, index filters aren't persistent and you cannot easily create index filters for all cluster nodes. 查询设置比索引筛选器具有更多功能。此外,索引筛选器不是持久的,您无法轻松为所有集群节点创建索引筛选器。To add query settings and explore examples, see setQuerySettings.要添加查询设置并探索示例,请参阅setQuerySettings

Find Cursor Behavior on Views在视图上查找游标行为

Starting in MongoDB 7.3, when you use a find command on a view with the singleBatch: true and batchSize: 1 options, a cursor is no longer returned. 从MongoDB 7.3开始,当您在具有singleBatch: truebatchSize:1选项的视图上使用find命令时,将不再返回游标。In previous versions of MongoDB these find queries would return a cursor even when you set the single batch option to true.在MongoDB的早期版本中,即使将单批处理选项设置为true,这些查找查询也会返回一个游标。

Query Settings查询设置

New in version 8.0.在版本8.0中新增。

You can use query settings to set index hints, set operation rejection filters, and other fields. 您可以使用查询设置来设置索引提示、设置操作拒绝筛选器和其他字段。The settings apply to the query shape on the entire cluster. The cluster retains the settings after shutdown.这些设置适用于整个集群上的查询形状。集群在关闭后保留设置。

The query optimizer uses the query settings as an additional input during query planning, which affects the plan selected to run the query. You can also use query settings to block a query shape.查询优化器在查询规划期间使用查询设置作为额外输入,这会影响为运行查询而选择的计划。您还可以使用查询设置来阻止查询形状。

To add query settings and explore examples, see setQuerySettings.要添加查询设置并探索示例,请参阅setQuerySettings

You can add query settings for find, distinct, and aggregate commands.您可以为finddistinctaggregate命令添加查询设置。

Query settings have more functionality and are preferred over deprecated index filters.查询设置具有更多功能,并且优于已弃用的索引筛选器

To remove query settings, use removeQuerySettings. To obtain the query settings, use a $querySettings stage in an aggregation pipeline.要删除查询设置,请使用removeQuerySettings。要获取查询设置,请在聚合管道中使用$querySettings阶段。

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.mongosh提供cursor.collation()来指定dbcollectionfund()操作的排序规则

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" }
} )