On this page本页内容
db.collection.
find
(query, projection)¶mongo
Shell Method
This page documents the 本页记录了mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. mongo
shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。
Selects documents in a collection or view and returns a cursor to the selected documents.选择集合或视图中的文档,并将游标返回到所选文档。
query |
document | {} ).{} )。 |
projection | document |
|
Returns: | query criteria. query 条件匹配的文档的游标。find() method “returns documents,” the method is actually returning a cursor to the documents.find() 方法“返回文档”时,该方法实际上是将游标返回到文档。 |
---|
Language Consistency语言一致性
Starting in MongoDB 4.4, as part of making 从MongoDB 4.4开始,作为使find
and findAndModify
projection consistent with aggregation’s $project
stage,find
和findAndModify
投影与聚合的$project
阶段保持一致的一部分,
find
and findAndModify
projection can accept aggregation expressions and syntax.find
和findAndModify
投影可以接受聚合表达式和语法。Projection Restrictions
for details.The projection
parameter determines which fields are returned in the matching documents. projection
参数确定匹配文档中返回的字段。The projection
parameter takes a document of the following form:projection
参数采用以下形式的文档:
<field>: <1 or true> |
|
<field>: <0 or false> |
|
"<field>.$": <1 or true> |
$ array projection operator, you can specify the projection to return the first element that match the query condition on the array field; e.g. "arrayField.$" : 1 . $ 数组投影运算符,可以指定投影以返回与数组字段上的查询条件匹配的第一个元素;亦即"arrayField.$" : 1 。 |
<field>: <array projection> |
$elemMatch , $slice , specifies the array element(s) to include, thereby excluding those elements that do not meet the expressions. $elemMatch 、$slice ,指定要包含的数组元素,从而排除那些不符合表达式的元素。 |
<field>: <$meta expression> |
$meta operator expression, specifies the inclusion of available per-document metadata . $meta 运算符表达式,指定包含每个文档可用的元数据。 |
<field>: <aggregation expression> |
|
For fields in an embedded documents, you can specify the field using either:对于嵌入文档中的字段,可以使用以下任一方法指定字段:
"field.nestedfield": <value>
{ field: { nestedfield: <value> } }
(_id
The 默认情况下,_id
field is included in the returned documents by default unless you explicitly specify _id: 0
in the projection to suppress the field._id
字段包含在返回的文档中,除非在投影中明确指定_id:0
以抑制该字段。
A projection
cannot contain both include and exclude specifications, with the exception of the _id
field:projection
不能同时包含包含和排除规范,但_id
字段除外:
_id
field is the only field that you can explicitly exclude._id
字段是唯一可以显式排除的字段。_id
field is the only field that you can explicitly include; however, the _id
field is included by default._id
字段是唯一可以显式包括的字段;但是,默认情况下会包含_id
字段。See Projection Examples.请参阅投影示例。
Executing 在db.collection.find()
in the mongo
shell automatically iterates the cursor to display up to the first 20 documents. mongo
shell中执行db.collection.find()
会自动迭代游标,最多显示前20个文档。Type 键入it
to continue iteration.it
以继续迭代。
To access the returned documents with a driver, use the appropriate cursor handling mechanism for the driver language.要使用驱动程序访问返回的文档,请使用驱动程序语言的适当游标处理机制。
To specify the read concern for 指定db.collection.find()
, use the cursor.readConcern()
method.db.collection.find()
的读取关注点,使用cursor.readConcern()
方法。
MongoDB treats some data types as equivalent for comparison purposes. 出于比较的目的,MongoDB将某些数据类型视为等价的。For instance, numeric types undergo conversion before comparison. 例如,数字类型在比较之前进行转换。For most data types, however, comparison operators only perform comparisons on documents where the BSON type of the target field matches the type of the query operand. 但是,对于大多数数据类型,比较运算符仅对目标字段的BSON类型与查询操作数类型匹配的文档执行比较。Consider the following collection:考虑下面的集合:
The following query uses 下面的查询使用$gt
to return documents where the value of qty
is greater than 4
.$gt
返回qty
值大于4的文档。
The query returns the following documents:查询将返回以下文档:
The document with 不返回_id
equal to "avocados"
is not returned because its qty
value is of type string
while the $gt
operand is of type integer
._id
等于"avocados"
的文档,因为其qty
值的类型为string
,而$gt
操作数的类型为integer
。
The document with 不返回_id
equal to "oranges"
is not returned because its qty
value is of type object
._id
等于"oranges"
的文档,因为其qty
值为object
类型。
Note
To enforce data types in a collection, use Schema Validation.要在集合中强制数据类型,请使用架构验证。
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 the 从MongoDB 3.6开始,MongoDB驱动程序和mongo
shell associate all operations with a server session, with the exception of unacknowledged write operations. 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. 如果会话空闲时间超过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
或maxTimeMS
(大于30分钟)的游标。
For operations that may be idle for longer than 30 minutes, associate the operation with an explicit session using 对于空闲时间可能超过30分钟的操作,请使用Session.startSession()
and periodically refresh the session using the refreshSessions
command. Session.startSession()
将该操作与显式会话关联,并使用refreshSessions
命令定期刷新会话。See 有关更多信息,请参阅会话空闲超时。Session Idle Timeout
for more information.
db.collection.find()
can be used inside multi-document transactions.可以在多文档事务中使用。
getMore
inside the transaction.getMore
。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大小限制),请参阅生产注意事项。
Starting in MongoDB 4.2, if the client that issued the 从MongoDB 4.2开始,如果发布db.collection.find()
disconnects before the operation completes, MongoDB marks the db.collection.find()
for termination (i.e. killOp
on the operation).db.collection.find()
的客户端在操作完成之前断开连接,MongoDB会标记db.collection.find()
终止(即操作上killOp
)。
The examples in this section use documents from the bios collection where the documents generally have the form:本节中的示例使用bios集合中的文档,这些文档通常具有以下格式:
To create and populate the 要创建和填充bios
collection, see The bios Example Collection.bios
集合,请参阅bios示例集合。
The 不带参数的find()
method with no parameters returns all documents from a collection and returns all fields for the documents. find()
方法返回集合中的所有文档,并返回文档的所有字段。For example, the following operation returns all documents in the bios collection:例如,以下操作将返回bios集合中的所有文档:
_id
equals 5
:_id
等于5:
last
in the name
embedded document equals "Hopper"
:last
字段等于"Hopper"
:
Note
To access fields in an embedded document, use dot notation (要访问嵌入文档中的字段,请使用点符号("<embedded document>.<field>"
)."<embedded document>.<field>"
)。
To find documents that match a set of selection criteria, call 要查找与一组选择条件匹配的文档,请使用find()
with the <criteria>
parameter.<criteria>
参数调用find()
。
MongoDB provides various query operators to specify the criteria.MongoDB提供了各种查询运算符来指定条件。
$in
operator to return documents in the bios collection where _id
equals either 5
or ObjectId("507c35dd8fada716c89d0013")
:$in
运算符返回bios集合中的文档,其中_id
等于5
或ObjectId("507c35dd8fada716c89d0013")
:
$gt
operator returns all the documents from the bios
collection where birth
is greater than new Date('1950-01-01')
:$gt
运算符返回bios
集合中birth
大于new Date('1950-01-01')
的所有文档:
$regex
operator to return documents in the bios collection where name.last
field starts with the letter N
(or is "LIKE N%"
)$regex
运算符返回bios集合中的文档,其中name.last
字段以字母N
开头(或是"LIKE N%"
)
For a list of the query operators, see Query Selectors.有关查询运算符的列表,请参阅查询选择器。
Combine comparison operators to specify ranges for a field. 组合比较运算符以指定字段的范围。The following operation returns from the bios collection documents where 以下操作从bios集合文档返回,其中出生日期介于birth
is between new Date('1940-01-01')
and new Date('1960-01-01')
(exclusive):new Date('1940-01-01')
和new Date('1960-01-01')
之间(不包括两者):
For a list of the query operators, see Query Selectors.有关查询运算符的列表,请参阅查询选择器。
The following operation returns all the documents from the bios collection where 以下操作返回bios集合中birth
field is greater than
new Date('1950-01-01')
and death
field does not exists:birth
字段大于new Date('1950-01-01')
且death
字段不存在的所有文档:
For a list of the query operators, see Query Selectors.有关查询运算符的列表,请参阅查询选择器。
The following examples query the 以下示例查询bios集合中的name
embedded field in the bios collection.name
嵌入字段。
The following operation returns documents in the bios collection where the embedded document 以下操作返回bios集合中的文档,其中嵌入的文档name
is exactly { first: "Yukihiro", last: "Matsumoto" }
, including the order:name
正好是{ first: "Yukihiro", last: "Matsumoto" }
,包括顺序:
The name
field must match the embedded document exactly. name
字段必须与嵌入的文档完全匹配。The query does not match documents with the following 查询与具有以下name
fields:name
字段的文档不匹配:
The following operation returns documents in the bios collection where the embedded document 下面的操作返回bios集合中的文档,其中嵌入的文档name
contains a field first
with the value "Yukihiro"
and a field last
with the value "Matsumoto"
. name
的first
字段包含一个值为"Yukihiro"
,last
字段包含一个值"Matsumoto"
。The query uses dot notation to access fields in an embedded document:查询使用点符号访问嵌入文档中的字段:
The query matches the document where the 查询将name
field contains an embedded document with the field first
with the value "Yukihiro"
and a field last
with the value "Matsumoto"
. name
字段中包含嵌入文档的文档与字段匹配,字段first
值为"Yukihiro"
,字段last
值为"Matsumoto"
。For instance, the query would match documents with 例如,查询会将文档与包含以下任一值的name
fields that held either of the following values:name
字段相匹配:
For more information and examples, see also Query on Embedded/Nested Documents.有关更多信息和示例,请参阅查询嵌入/嵌套文档。
The following examples query the 以下示例查询bios集合中的contribs
array in the bios collection.contribs
阵列。
contribs
contains the element "UNIX"
:contribs
包含元素"UNIX"
:
contribs
contains the element "ALGOL"
or "Lisp"
:contribs
包含元素"ALGOL"
或"Lisp"
:
$all
query operator to return documents in the bios collection where the array field contribs
contains both the elements "ALGOL"
and "Lisp"
:$all
查询运算符返回bios集合中的文档,其中数组字段contribs
包含元素"ALGOL"
和"Lisp"
:
For more examples, see 有关更多示例,请参阅$all
. $all
。See also 另请参见$elemMatch
.$elemMatch
。
$size
operator to return documents in the bios collection where the array size of contribs
is 4:$size
运算符返回bios集合中的文档,其中contribs
的数组大小为4:
For more information and examples of querying an array, see:有关查询数组的更多信息和示例,请参阅:
For a list of array specific query operators, see Array.有关特定于数组的查询运算符的列表,请参阅数组。
The following examples query the 以下示例查询bios集合中的awards
array in the bios collection.awards
数组。
awards
array contains an element with award
field equals "Turing Award"
:awards
数组包含award
字段等于"Turing Award"
的元素:
awards
array contains at least one element with both the award
field equals "Turing Award"
and the year
field greater than 1980:awards
数组至少包含一个元素,其award
字段等于"Turing Award"
,year
字段大于1980
:
Use the 使用$elemMatch
operator to specify multiple criteria on an array element.$elemMatch
运算符在数组元素上指定多个条件。
For more information and examples of querying an array, see:有关查询数组的更多信息和示例,请参阅:
For a list of array specific query operators, see Array.有关特定于数组的查询运算符的列表,请参阅数组。
The projection parameter specifies which fields to return. projection
参数指定要返回的字段。The parameter contains either include or exclude specifications, not both, unless the exclude is for the 参数包含_id
field.include
或exclude
规范,而不是两者,除非exclude
是针对_id
字段的。
Note
Unless the 除非投影文档_id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned._id:0
中明确排除了_id
字段,否则将返回_id
字段。
The following operation finds all documents in the bios collection and returns only the 以下操作将查找bios集合中的所有文档,并仅返回name
field, contribs
field and _id
field:name
字段、contribs
字段和_id
字段:
Note
Unless the 除非投影文档_id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned._id:0
中明确排除了_id
字段,否则将返回_id
字段。
The following operation queries the bios collection and returns all fields except the 以下操作查询bios集合并返回所有字段,但first
field in the name
embedded document and the birth
field:name
嵌入文档中的first
字段和birth
字段除外:
_id
Field_id
字段¶Note
Unless the 除非投影文档_id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned._id:0
中明确排除了_id
字段,否则将返回_id
字段。
The following operation finds documents in the bios collection and returns only the 以下操作在bios集合中查找文档,并仅返回name
field and the contribs
field:name
字段和contribs
字段:
The following operation queries the bios collection and returns the 以下操作查询bios集合,并返回last
field in the name
embedded document and the first two elements in the contribs
array:name
嵌入文档中的last
字段和contribs
数组中的前两个元素:
Starting in MongoDB 4.4, you can also specify embedded fields using the nested form, e.g.从MongoDB 4.4开始,还可以使用嵌套形式指定嵌入字段,例如。
Starting in MongoDB 4.4, 从MongoDB 4.4开始,db.collection.find()
projection can accept aggregation expressions and syntax.db.collection.find()
投影可以接受聚合表达式和语法。
With the use of aggregation expressions and syntax, you can project new fields or project existing fields with new values. 通过使用聚合表达式和语法,可以投影新字段或使用新值投影现有字段。For example, the following operation uses aggregation expressions to override the value of the 例如,以下操作使用聚合表达式覆盖name
and awards
fields as well as to include new fields reportDate
, reportBy
, and reportNumber
.name
和awards
字段的值,并包括新字段reportDate
、reportBy
和reportNumber
。
To set the 要将reportRun
field to the value 1
The operation returns the following documents:reportRun
字段设置为值1
,操作将返回以下文档:
The find()
method returns a cursor to the results.find()
方法返回指向结果的游标。
In the 在mongo
shell, if the returned cursor is not assigned to a variable using the var
keyword, the cursor is automatically iterated to access up to the first 20 documents that match the query. mongo
shell中,如果返回的游标没有使用var
关键字分配给变量,则会自动迭代游标,以访问与查询匹配的前20个文档。You can set the 可以设置DBQuery.shellBatchSize
variable to change the number of automatically iterated documents.DBQuery.shellBatchSize
变量来更改自动迭代文档的数量。
To manually iterate over the results, assign the returned cursor to a variable with the 要手动迭代结果,请将返回的游标分配给带有var
keyword, as shown in the following sections.var
关键字的变量,如以下部分所示。
The following example uses the variable 以下示例使用变量myCursor
to iterate over the cursor and print the matching documents:myCursor
在游标上迭代并打印匹配的文档:
The mongo
shell and the drivers provide several cursor methods that call on the cursor returned by the find()
method to modify its behavior.mongo
shell和驱动程序提供了几个游标方法,这些方法调用find()
方法返回的cursor来修改其行为。
The sort()
method orders the documents in the result set. sort()
方法对结果集中的文档进行排序。The following operation returns documents in the bios collection sorted in ascending order by the 以下操作返回bios集合中按name
field:name
字段升序排序的文档:
sort()
corresponds to the 对应于SQL中的ORDER BY
statement in SQL.ORDER BY
语句。
The limit()
method limits the number of documents in the result set. limit()
方法限制结果集中的文档数。The following operation returns at most 以下操作在bios集合中最多返回5
documents in the bios collection:5
个文档:
limit()
corresponds to the 对应于SQL中的limit语句。LIMIT
statement in SQL.
The skip()
method controls the starting point of the results set. skip()
方法控制结果集的起点。The following operation skips the first 以下操作跳过bios集合中的前5
documents in the bios collection and returns all remaining documents:5
个文档,并返回所有剩余文档:
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。
The collation()
method specifies the collation for the db.collection.find()
operation.collation()
方法指定db.collection.find()
操作的排序规则。
The following statements chain cursor methods 以下语句链接游标方法limit()
and sort()
:limit()
和sort()
:
The two statements are equivalent; i.e. the order in which you chain the 这两种说法是等价的;例如,将limit()
and the sort()
methods is not significant. limit()
和sort()
方法链接起来的顺序并不重要。Both statements return the first five documents, as determined by the ascending sort order on ‘name’.这两条语句都返回前五个文档,由“name”的升序顺序决定。
mongo
Shell Cursor Methodsmongo
Shell游标方法¶