On this page本页内容
find
Executes a query and returns the first batch of results and the cursor id, from which the client can construct a cursor.执行查询并返回第一批结果和游标id,客户端可以从中构造游标。
Rather than run the 您可以使用find
command directly, you can use the db.collection.find()
helper provided in mongosh
or the equivalent helper in the drivers.mongosh
中提供的db.collection.find()
助手或驱动程序中的等效助手,而不是直接运行find
命令。
Changed in version 4.4.在版本4.4中更改。
oplogReplay
option to the find
command. find
命令的oplogReplay
选项。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 } )
The command accepts the following fields:该命令接受以下字段:
find | string | |
filter | document | |
document | ||
projection | document |
|
hint | string or document |
|
skip | Positive integer | |
limit | Non-negative integer | |
batchSize | non-negative integer |
|
singleBatch | boolean | false 。 |
comment | any |
|
maxTimeMS | positive integer |
|
readConcern | document |
|
max | document |
|
min | document |
|
returnKey | boolean | true ,则只返回结果文档中的索引键。false 。returnKey is true and the find command does not use an index, the returned documents will be empty. 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. getMore 选项一起使用,如果在数据结束时而不是返回任何数据,则可以暂时阻止游标上的getMore命令。find returns as normal. find 返回正常。 |
oplogReplay | boolean |
{ find: "data", oplogReplay: true, filter: { ts: { $gte: new Timestamp(1514764800, 0) } } }
|
noCursorTimeout | boolean | |
allowPartialResults | boolean |
|
collation | document |
collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean> }
|
boolean |
| |
let | document |
{ <variable_name_1>: <expression_1>, ..., <variable_name_n>: <expression_n> }
|
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 |
|
"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()
结果。
$regex
Starting in MongoDB 5.1, invalid 从MongoDB 5.1开始,不再忽略无效的$regex options
options are no longer ignored. $regex options
选项。This change makes 此更改使$regex options
more consistent with the use of $regex
in the aggregate
command and projection queries.$regex options
与aggregate
命令和projection
查询中使用$regex
更加一致。
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
。
Starting in MongoDB 3.6, MongoDB drivers and 从MongoDB 3.6开始,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. 如果会话空闲时间超过30分钟,MongoDB服务器会将该会话标记为过期,并可以随时关闭。When the MongoDB server closes the session, it also kills any in-progress operations and open cursors associated with the session. 当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.有关详细信息,请参阅会话空闲超时。
find
can be used inside multi-document transactions.可以在多文档事务中使用。
getMore
inside the transaction.getMore
。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.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
Starting in MongoDB 4.2, if the client that issued the 从MongoDB 4.2开始,如果发出find
disconnects before the operation completes, MongoDB marks the find
for termination (i.e. killOp
on the operation).find
的客户端在操作完成之前断开连接,MongoDB将find
标记为终止(即操作上的killOp
)。
When using Stable API V1, the following 使用稳定API V1时,不支持以下find
command fields are not supported:find
命令字段:
awaitData
max
min
noCursorTimeout
oplogReplay
returnKey
showRecordId
tailable
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._id
、name
、name
和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 } )
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.有关可用读取关注的更多信息,请参阅读取关注。
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()
来指定db.collection.find()
操作的排序规则。
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" } } )