find

On this page本页内容

Definition定义

find

New in version 3.2.版本3.2中的新功能。

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 the mongo shell or the equivalent helper in the drivers.您可以使用mongo shell中提供的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语法如下所示:

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

Command Fields命令字段

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

Field字段Type类型Description描述
find string The name of the collection or view to query.要查询的集合或视图的名称。
filter document 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.用于结果排序的排序规范。
projection document

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()操作不支持以下投影运算符

hint string 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;如果筛选器是_id字段{_id: <value> }上的相等条件,则min和/或max不需要hint

skip Positive integer Optional.可选。Number of documents to skip. 要跳过的文档数。Defaults to 0.默认值为0。
limit Non-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相当于不设置限制。
batchSize non-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.与之前的wire协议版本不同,find命令的batchSize1时不会关闭游标。

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

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之前,注释只能是字符串。

maxTimeMS positive 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. 指定可线性化读取关注点时,如果大多数数据承载成员不可用,请始终使用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.maxTimeMS确保操作不会无限期阻塞,而是确保在无法满足读取问题时,操作返回错误。

readConcern document

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

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

Possible read concern levels are:可能的阅读关注级别包括:

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级别。

max document

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,除非指定的filter_id字段{ _id: <value> }上的相等条件。

min document

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,除非指定的筛选器是_id字段{ _id: <value> }上的相等条件。

returnKey boolean Optional.可选。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.如果returnKey为truefind命令不使用索引,则返回的文档将为空。
showRecordId boolean Optional.可选。Determines whether to return the record identifier for each document. 确定是否返回每个文档的记录标识符。If true, adds a field $recordId to the returned documents.如果为true,则在返回的文档中添加字段$recordId。
tailable boolean Optional.可选。Returns a tailable cursor for a capped collections.返回封顶集合的可裁剪游标
awaitData boolean Optional.可选。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将正常返回。
oplogReplay boolean

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:

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

Deprecated

Changed in version 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. If specified, the server accepts the oplogReplay flag for backwards compatibility, but the flag has no effect.如果指定,服务器将接受oplogReplay标志以实现向后兼容性,但该标志无效。

noCursorTimeout boolean Optional.可选。Prevents the server from timing out idle cursors after an inactivity period (10 minutes).防止服务器在非活动期(10分钟)后超时空闲游标。
allowPartialResults boolean

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.

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.

collation document

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.例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一种排序规则,对排序使用另一种排序规则。

New in version 3.4.版本3.4中的新功能。

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.

For more complete documentation on allowDiskUse, see cursor.allowDiskUse().

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

New in version 4.4.版本4.4中的新功能。

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. 要返回部分结果,而不是由于查询的碎片不可用而导致的错误,必须在allowPartialResults设置为true的情况下运行find命令。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.

"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.

Behavior行为

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

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.这包括配置了noCursorTimeoutmaxTimeMS(大于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 Session.startSession() and periodically refresh the session using the refreshSessions command. 对于返回游标的操作,如果游标空闲时间可能超过30分钟,请使用Session.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会将查找标记为终止(即在操作上killOp)。

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"读取关注点,以读取确认已写入多数节点的数据的最新副本。

To use read concern level of "majority", replica sets must use WiredTiger storage engine.

You can disable read concern "majority" for a deployment with a three-member primary-secondary-arbiter (PSA) architecture; however, this has implications for change streams (in MongoDB 4.0 and earlier only) and transactions on sharded clusters. For more information, see Disable Read Concern 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.

A readConcern can be specified for the mongo shell method db.collection.find() using the cursor.readConcern method:

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

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

Specify Collation指定排序规则

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.允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。

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

The mongo shell provides the cursor.collation() to specify collation for a db.collection.find() operation.mongo shell提供cursor.collation()来为db.collection.find()操作指定排序规则。