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,客户端可以从中构造游标。TipIn在mongosh
, this command can also be run through thedb.collection.find()
ordb.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 MongoDB将oplogReplay
option to the find
command. 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:该命令接受以下字段:
find | string | |
filter | document | |
sort | document | |
projection | document | find() |
hint | string or document | 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 。 |
skip | Positive integer | |
limit | Non-negative integer | |
batchSize | non-negative integer | 101 。batchSize 为0表示将建立游标,但第一批中不会返回任何文档。find command does not close the cursor. find 命令的batchSize 为1不会关闭游标。 |
singleBatch | boolean | false 。 |
comment | any |
Note |
maxTimeMS | non-negative integer | maxTimeMS , operations will not time out. A value of 0 explicitly specifies the default unbounded behavior.maxTimeMS 的值,操作将不会超时。值0 显式指定默认的无边界行为。db.killOp() . db.killOp() 相同的机制终止超过指定时间限制的操作。Tip linearizable read concern , always use maxTimeMS in case a majority of data bearing members are unavailable. linearizable 的读取关注时,如果大多数数据承载成员不可用,请始终使用maxTimeMS 。maxTimeMS |
readConcern | document | readConcern: { level: <value> }
getMore command uses the readConcern level specified in the originating find command. getMore 命令使用原始find 命令中指定的readConcern 级别。 |
max | document | cursor.max() for details.cursor.max() 。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> } 。 |
min | document | cursor.min() for details.cursor.min() 。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> } 。 |
returnKey | boolean | find command does not use an index, the returned documents will be empty.true ,则仅返回结果文档中的索引键。默认值为false 。如果returnKey为true ,并且find 命令不使用索引,则返回的文档将为空。 |
showRecordId | boolean | true ,则在返回的文档中添加字段$recordId 。 |
tailable | boolean | |
awaitData | boolean | getMore command on the cursor temporarily if at the end of data rather than returning no data. tailable 选项一起使用可以临时阻止游标上的getMore 命令,而不是不返回任何数据。find returns as normal.find 将正常返回。 |
oplogReplay | boolean | oplogReplay , the find field must provide a filter option comparing the ts document field to a timestamp using one of the following comparison operators: oplogReplay ,find 字段必须提供一个filter 选项,使用以下比较运算符之一将ts 文档字段与timestamp 进行比较:
data capped collection with a timestamp later than or equal to January 1st, 2018 UTC: data 封顶集合中的文档:
{ find: "data", Note DeprecatedoplogReplay field is deprecated. 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的存储格式来更有效地执行命令。oplogReplay flag for backwards compatibility, but the flag has no effect. oplogReplay 标志以实现向后兼容性,但该标志无效。 |
noCursorTimeout | boolean | |
allowPartialResults | boolean | getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable.getMore 命令)返回部分结果,而不是错误。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 指示符字段。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 。 |
collation | document | collation collation 选项具有以下语法:
collation: { locale field is mandatory; all other collation fields are optional. locale 字段是必需的;所有其他排序规则字段都是可选的。db.createCollection() ), the operation uses the collation specified for the collection.db.createCollection() ),则操作将使用为集合指定的排序规则。 |
allowDiskUse | boolean | allowDiskUseByDefault for a specific query. You can use this option to either: allowDiskUseByDefault 。您可以使用此选项执行以下操作之一:
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 } .allowDiskUseByDefault 设置为true ,并且服务器在管道执行阶段需要超过100兆字节的内存,MongoDB会自动将临时文件写入磁盘,除非查询指定{ allowDiskUse: false } 。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.sort ,或者阻塞排序所需的内存少于100兆字节,那么allowDiskUse 就没有作用。allowDiskUse , see cursor.allowDiskUse() .allowDiskUse 的更多完整文档,请参阅cursor.allowDiskUse() 。 |
let | document | { <variable_name_1>: <expression_1>, $$ ) together with your variable name in the form $$<variable_name> . $$ )和形式为$$<variable_name> 的变量名。$$targetTotal . $$targetTotal 。Note let and variables, see Use Variables in let . let 和变量的完整示例,请参阅在let 中使用变量。 |
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")
}
}
}
cursor | id and the firstBatch of documents.id 和文档的firstBatch 。cursor document includes a partialResultsReturned field. cursor 文档包括一个partialResultsReturned 字段。find command must run with allowPartialResults set to true . find 命令必须在allowPartialResults 设置为true 的情况下运行。allowPartialResults 。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" | 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 从MongoDB 5.1开始,不再忽略无效的$regex options
options are no longer ignored. $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 MongoDB驱动程序和mongosh
associate all operations with a server session, with the exception of unacknowledged write operations. 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 对于返回游标的操作,如果游标空闲时间可能超过30分钟,请使用Mongo.startSession()
and periodically refresh the session using the refreshSessions
command. 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
。
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 从MongoDB 4.2开始,如果发出find
disconnects before the operation completes, MongoDB marks find
for termination using killOp
.find
的客户端在操作完成之前断开连接,MongoDB会使用killOp
标记find
终止。
Stable API
When using Stable API V1, the following 使用Stable API V1时,不支持以下find
command fields are not supported: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 从MongoDB 6.0开始,索引筛选器使用之前使用planCacheSetFilter
command.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
,只返回匹配文档中的以下字段:_id
、name
、rating
和address
字段。
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 let
在let
中使用变量
let
New in version 5.0. 5.0版新增。
To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他地方访问的变量,请使用let
选项。
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" }
} )