Definition定义
findExecutes 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 thedb.collection.find()ordb.collection.findOne()helper methods.mongosh中,此命令也可以通过db.collection.find()或db.collection.findOne()辅助方法运行。Helper methods are convenient for助手方法对mongoshusers, 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 从MongoDB 4.4开始,find command ignores the oplogReplay flag. 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:该命令接受以下字段:
find | ||
filter | ||
projection |
| |
hint |
| |
skip | ||
limit | ||
batchSize |
| |
| false。 | |
comment |
| |
maxTimeMS |
| |
readConcern |
| |
max |
| |
min |
| |
returnKey | true,则仅返回结果文档中的索引键。默认值为false。find command does not use an index, the returned documents will be empty.returnKey为true并且find命令不使用索引,则返回的文档将为空。 | |
showRecordId | true,则向返回的文档添加字段$recordId。 | |
tailable | ||
awaitData | getMore command on the cursor temporarily at the end of data rather than returning no data. getMore命令,而不是不返回任何数据。find returns as normal.find将正常返回。 | |
noCursorTimeout | ||
allowPartialResults |
| |
collation |
| |
| ||
let |
|
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")
}
}
}
cursor |
|
"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()还包括副本集和分片集群的以下信息:
$clusterTimeoperationTime
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 从MongoDB 5.1开始,无效的$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.$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 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()或大于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 对于返回游标的操作,如果游标可能空闲超过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 distributed transactions.find可以在分布式事务中使用。
For cursors created outside of a transaction, you cannot call对于在事务外部创建的游标,您不能在事务内部调用getMoreinside the transaction.getMore。For cursors created in a transaction, you cannot call对于在事务中创建的游标,您不能在事务外部调用getMoreoutside 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 使用Stable API V1时,不支持以下find command fields are not supported:find命令字段:
awaitDatamaxminnoCursorTimeoutreturnKeyshowRecordIdtailable
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命令设置的排序规则。
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 从MongoDB 7.3开始,当您在具有singleBatch: true and batchSize: 1 options, a cursor is no longer returned. singleBatch: true和batchSize:1选项的视图上使用find命令时,将不再返回游标。In previous versions of MongoDB these find queries would return a cursor even when you set the single batch option to 在MongoDB的早期版本中,即使将单批处理选项设置为true.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.find、distinct和aggregate命令添加查询设置。
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,仅返回匹配文档中的以下字段:_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.mongosh提供cursor.collation()来指定dbcollectionfund()操作的排序规则。
Use Variables in let在let中使用变量
letNew in version 5.0.在版本5.0中新增。
To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他地方访问的变量,请使用let选项。
Note
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" }
} )