db.collection.find()
On this page本页内容
Definition定义
db.collection.find(query, projection, options)
- Important
mongosh Method
This page documents a本页记录了一个mongosh
method. This is not the documentation for database commands or language-specific drivers, such as Node.js.mongosh
方法。这不是数据库命令或特定语言驱动程序(如Node.js)的文档。For the database command, see the
find
command.For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.
For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:Selects documents in a collection or view and returns a cursor to the selected documents.选择集合或视图中的文档,并将游标返回到所选文档。Parameter参数Type类型Description描述query
document Optional.可选的。Specifies selection filter using query operators.使用查询运算符指定选择筛选器。To return all documents in a collection, omit this parameter or pass an empty document (若要返回集合中的所有文档,请省略此参数或传递一个空文档({}
).{}
)。projection
document Optional.可选的。Specifies the fields to return in the documents that match the query filter.指定要在与查询筛选器匹配的文档中返回的字段。To return all fields in the matching documents, omit this parameter.若要返回匹配文档中的所有字段,请省略此参数。For details, see Projection.有关详细信息,请参阅投影。options
document Optional.可选的。Specifies additional options for the query. These options modify query behavior and how results are returned.指定查询的其他选项。这些选项修改查询行为以及返回结果的方式。To see available options, see FindOptions.要查看可用选项,请参阅FindOptions
。Returns:返回值:A cursor to the documents that match the指向与查询条件匹配的文档的query
criteria. When thefind()
method "returns documents," the method is actually returning a cursor to the documents.cursor
。当find()
方法“返回文档”时,该方法实际上是将游标返回到文档。
Behavior行为
Projection投影
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
阶段一致的一部分,
Thefind()
andfindAndModify()
projection can accept aggregation expressions and syntax.find()
和findAndModify()
投影可以接受聚合表达式和语法。MongoDB enforces additional restrictions with regards to projections.MongoDB对投影实施了额外的限制。See 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
参数采用以下形式的文档:
{ <field1>: <value>, <field2>: <value> ... }
<field>: <1 or true> | true .true 。 |
<field>: <0 or false> | |
"<field>.$": <1 or true> | $ array projection operator to return the first element that matches the query condition on the array field. $ 数组投影运算符返回与数组字段上的查询条件匹配的第一个元素。true .true 。 |
<field>: <array projection> | $elemMatch , $slice ) to specify the array elements to include.$elemMatch ,$slice )指定要包含的数组元素。 |
<field>: <$meta expression> | $meta operator expression to specify the inclusion of available per-document metadata .$meta 运算符表达式指定包含可用的每个文档元数据。 |
<field>: <aggregation expression> |
true or false to indicate the inclusion or exclusion of the field. true 或false ,以指示包含或排除字段。 |
Embedded Field Specification嵌入式现场规范
For fields in an embedded documents, you can specify the field using either:对于嵌入文档中的字段,可以使用以下任一项指定字段:
dot notation点记号法, for example例如"field.nestedfield": <value>
nested form, for example嵌套形式,例如{ field: { nestedfield: <value> } }
(Starting in MongoDB 4.4){ field: { nestedfield: <value> } }
(从MongoDB 4.4开始)
_id
Field Projection字段投影
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
以取消显示该字段。
Inclusion or Exclusion包含或排除
A projection
cannot contain both include and exclude specifications, with the exception of the _id
field:projection
不能同时包含include和exclude规范,_id
字段除外:
In projections that explicitly include fields, the在显式包含字段的投影中,_id
field is the only field that you can explicitly exclude._id
字段是唯一可以显式排除的字段。In projections that explicitly excludes fields, the在显式排除字段的投影中,_id
field is the only field that you can explicitly include; however, the_id
field is included by default._id
字段是唯一可以显式包含的字段;但是,_id
字段在默认情况下是包含在内的。
See Projection Examples.请参见投影示例。
Cursor Handling游标处理
Executing 在db.collection.find()
in mongosh
automatically iterates the cursor to display up to the first 20 documents. Type it
to continue iteration.mongosh
中执行db.collection.find()
会自动迭代游标,最多显示前20个文档。键入it
以继续迭代。
To access the returned documents with a driver, use the appropriate cursor handling mechanism for the driver language.要使用驱动程序访问返回的文档,请为驱动程序语言使用适当的游标处理机制。
Read Concern读取关注
To specify the read concern for 要指定db.collection.find()
, use the cursor.readConcern()
method.db.collection.find()
的读取关注,请使用cursor.readConcern()
方法。
Type Bracketing类型归并
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:考虑以下集合:
{ "_id": "apples", "qty": 5 }
{ "_id": "bananas", "qty": 7 }
{ "_id": "oranges", "qty": { "in stock": 8, "ordered": 12 } }
{ "_id": "avocados", "qty": "fourteen" }
The following query uses 以下查询使用$gt
to return documents where the value of qty
is greater than 4
.$gt
返回qty
值大于4
的文档。
db.collection.find( { qty: { $gt: 4 } } )
The query returns the following documents:查询返回以下文档:
{ "_id": "apples", "qty": 5 }
{ "_id": "bananas", "qty": 7 }
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
类型。
To enforce data types in a collection, use Schema Validation.若要强制集合中的数据类型,请使用架构验证。
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. 如果会话空闲时间超过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分钟的操作,请使用Mongo.startSession()
and periodically refresh the session using the refreshSessions
command. Mongo.startSession()
将该操作与显式会话关联,并使用refreshSessions
命令定期刷新会话。See Session Idle Timeout for more information.有关详细信息,请参阅会话空闲超时。
Transactions事务
db.collection.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开始,如果发出db.collection.find()
disconnects before the operation completes, MongoDB marks db.collection.find()
for termination using killOp
.db.collection.find()
的客户端在操作完成之前断开连接,MongoDB会使用killOp
标记db.collection.find()
终止。
Examples实例
The examples in this section use documents from the bios collection where the documents generally have the form:本节中的示例使用bios
集合中的文档,其中文档通常具有以下形式:
{
"_id" : <value>,
"name" : { "first" : <string>, "last" : <string> }, // embedded document
"birth" : <ISODate>,
"death" : <ISODate>,
"contribs" : [ <string>, ... ], // Array of Strings
"awards" : [
{ "award" : <string>, year: <number>, by: <string> } // Array of embedded documents
...
]
}
To create and populate the 要创建和填充bios
collection, see bios collection.bios
集合,请参阅bios
集合。
Find All Documents in a Collection查找集合中的所有文档
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
集合中的所有文档:
db.bios.find()
Find Documents that Match Query Criteria查找符合查询条件的文档
Query for Equality查询相等
The following operation returns documents in the bios collection where以下操作返回_id
equals5
:bios
集合中_id
等于5
的文档:db.bios.find( { _id: 5 } )
The following operation returns documents in the bios collection where the field以下操作返回last
in thename
embedded document equals"Hopper"
:bios
集合中的文档,其中名称嵌入文档中的最后一个字段等于"Hopper"
:db.bios.find( { "name.last": "Hopper" } )
NoteTo access fields in an embedded document, use dot notation (要访问嵌入文档中的字段,请使用点记号法("<embedded document>.<field>"
)."<embedded document>.<field>"
)。
Query Using Operators使用运算符查询
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提供了各种查询运算符来指定条件。
The following operation uses the以下操作使用$in
operator to return documents in the bios collection where_id
equals either5
orObjectId("507c35dd8fada716c89d0013")
:$in
运算符返回bios
集合中的文档,其中_id
等于5
或ObjectId("507c35dd8fada716c89d0013")
:db.bios.find(
{ _id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] } }
)The following operation uses the以下操作使用$gt
operator returns all the documents from thebios
collection wherebirth
is greater thannew Date('1950-01-01')
:$gt
运算符返回bios
集合中birth
大于new Date('1950-01-01')
的所有文档:db.bios.find( { birth: { $gt: new Date('1950-01-01') } } )
The following operation uses the以下操作使用$regex
operator to return documents in the bios collection wherename.last
field starts with the letterN
(or is"LIKE N%"
)$regex
运算符返回bios
集合中的文档,其中name.last
字段以字母N
开头(或为"LIKE N%"
)db.bios.find(
{ "name.last": { $regex: /^N/ } }
)
For a list of the query operators, see Query Selectors.有关查询运算符的列表,请参阅查询选择器。
Query for Ranges查询范围
Combine comparison operators to specify ranges for a field. 组合比较运算符可以指定字段的范围。The following operation returns from the bios collection documents where 以下操作从birth
is between new Date('1940-01-01')
and new Date('1960-01-01')
(exclusive):bios
集合文档返回,其中birth
介于new Date('1940-01-01')
和new Date('1960-01-01')
之间(不包括):
db.bios.find( { birth: { $gt: new Date('1940-01-01'), $lt: new Date('1960-01-01') } } )
For a list of the query operators, see Query Selectors.有关查询运算符的列表,请参阅查询选择器。
Query for Multiple Conditions查询多个条件
The following operation returns all the documents from the bios collection where 以下操作返回birth
field is greater than
new Date('1950-01-01')
and death
field does not exists:bios
集合中birth
字段大于new Date('1950-01-01')
且death
字段不存在的所有文档:
db.bios.find( {
birth: { $gt: new Date('1920-01-01') },
death: { $exists: false }
} )
For a list of the query operators, see Query Selectors.有关查询运算符的列表,请参阅查询选择器。
Query Embedded Documents查询嵌入文档
The following examples query the 以下示例查询name
embedded field in the bios collection.bios
集合中的name
嵌入字段。
Query Exact Matches on Embedded Documents查询嵌入文档上的精确匹配
The following operation returns documents in the bios collection where the embedded document 以下操作返回name
is exactly { first: "Yukihiro", last: "Matsumoto" }
, including the order:bios
集合中嵌入的文档name
正好是{ first: "Yukihiro", last: "Matsumoto" }
的文档,包括顺序:
db.bios.find(
{ 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
字段的文档不匹配:
{
first: "Yukihiro",
aka: "Matz",
last: "Matsumoto"
}
{
last: "Matsumoto",
first: "Yukihiro"
}
Query Fields of an Embedded Document嵌入文档的查询字段
The following operation returns documents in the bios collection where the embedded document 以下操作返回name
contains a field first
with the value "Yukihiro"
and a field last
with the value "Matsumoto"
. bios
集合中的文档,其中嵌入的文档name
包含first
字段值为"Yukihiro"
,last
字段值为"Matsumoto"
。The query uses dot notation to access fields in an embedded document:查询使用点记号法访问嵌入文档中的字段:
db.bios.find(
{
"name.first": "Yukihiro",
"name.last": "Matsumoto"
}
)
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
字段的文档:
{
first: "Yukihiro",
aka: "Matz",
last: "Matsumoto"
}
{
last: "Matsumoto",
first: "Yukihiro"
}
For more information and examples, see also Query on Embedded/Nested Documents.有关更多信息和示例,请参阅查询嵌入/嵌套文档。
Query Arrays查询数组
Query for an Array Element查询数组元素
The following examples query the 以下示例查询contribs
array in the bios collection.bios
集合中的contribs
数组。
The following operation returns documents in the bios collection where the array field以下操作返回contribs
contains the element"UNIX"
:bios
集合中的文档,其中数组字段contribs
包含元素"UNIX"
:db.bios.find( { contribs: "UNIX" } )
The following operation returns documents in the bios collection where the array field以下操作返回contribs
contains the element"ALGOL"
or"Lisp"
:bios
集合中的文档,其中数组字段contribs
包含元素"ALGOL"
或"Lisp"
:db.bios.find( { contribs: { $in: [ "ALGOL", "Lisp" ]} } )
The following operation use the以下操作使用$all
query operator to return documents in the bios collection where the array fieldcontribs
contains both the elements"ALGOL"
and"Lisp"
:$all
查询运算符返回bios
集合中的文档,其中数组字段contribs
同时包含元素"ALGOL"
和"Lisp"
:db.bios.find( { contribs: { $all: [ "ALGOL", "Lisp" ] } } )
For more examples, see有关更多示例,请参阅$all
. See also$elemMatch
.$all
。另请参阅$elemMatch
。The following operation uses the以下操作使用$size
operator to return documents in the bios collection where the array size ofcontribs
is 4:$size
运算符返回bios
集合中的文档,其中contribs
的数组大小为4
:db.bios.find( { contribs: { $size: 4 } } )
For more information and examples of querying an array, see:有关查询数组的更多信息和示例,请参阅:
For a list of array specific query operators, see Array.有关特定于数组的查询运算符的列表,请参阅数组。
Query an Array of Documents查询文档数组
The following examples query the 以下示例查询awards
array in the bios collection.bios
集合中的awards
数组。
The following operation returns documents in the bios collection where the以下操作返回awards
array contains an element withaward
field equals"Turing Award"
:bios
集合中的文档,其中awards
数组包含一个元素,award
字段等于"Turing Award"
(图灵奖):db.bios.find(
{ "awards.award": "Turing Award" }
)The following operation returns documents in the bios collection where the以下操作返回awards
array contains at least one element with both theaward
field equals"Turing Award"
and theyear
field greater than 1980:bios
集合中的文档,其中awards
数组至少包含一个元素,其中award
字段等于"Turing Award"
,year
字段大于1980
:db.bios.find(
{ awards: { $elemMatch: { award: "Turing Award", year: { $gt: 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.有关特定于数组的查询运算符的列表,请参阅数组。
Projections投影
The projection parameter specifies which fields to return. 投影参数指定要返回的字段。The parameter contains either include or exclude specifications, not both, unless the exclude is for the 参数包含include或exclude规范,而不是两者都包含,除非exclude用于_id
field._id
字段。
Unless the 除非在投影文档_id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned._id
:0中明确排除_id
字段,否则返回_id
字段。
Specify the Fields to Return指定要返回的字段
The following operation finds all documents in the bios collection and returns only the 以下操作查找name
field, contribs
field and _id
field:bios
集合中的所有文档,并仅返回name
字段、contribs
字段和_id
字段:
db.bios.find( { }, { name: 1, contribs: 1 } )
Unless the 除非在投影文档_id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned._id
:0中明确排除_id
字段,否则返回_id
字段。
Explicitly Excluded Fields明确排除的字段
The following operation queries the bios collection and returns all fields except the 以下操作查询first
field in the name
embedded document and the birth
field:bios
集合并返回除name
嵌入文档中的first
字段和birth
字段之外的所有字段:
db.bios.find(
{ contribs: 'OOP' },
{ 'name.first': 0, birth: 0 }
)
Explicitly Exclude the _id
Field显式排除_id
字段
_id
FieldUnless 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 以下操作在name
field and the contribs
field:bios
集合中查找文档,并仅返回name
字段和contribs
字段:
db.bios.find(
{ },
{ name: 1, contribs: 1, _id: 0 }
)
On Arrays and Embedded Documents数组与嵌入式文档
The following operation queries the bios collection and returns the 以下操作查询last
field in the name
embedded document and the first two elements in the contribs
array:bios
集合,并返回name
嵌入文档中的last
字段和contribs
数组中的前两个元素:
db.bios.find(
{ },
{ _id: 0, 'name.last': 1, contribs: { $slice: 2 } } )
Starting in MongoDB 4.4, you can also specify embedded fields using the nested form, for example:从MongoDB 4.4开始,您还可以使用嵌套形式指定嵌入字段,例如:
db.bios.find(
{ },
{ _id: 0, name: { last: 1 }, contribs: { $slice: 2 } }
)
Use Aggregation Expression使用聚合表达式
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
。
db.bios.find(
{ },
{
_id: 0,
name: {
$concat: [
{ $ifNull: [ "$name.aka", "$name.first" ] },
" ",
"$name.last"
]
},
birth: 1,
contribs: 1,
awards: { $cond: { if: { $isArray: "$awards" }, then: { $size: "$awards" }, else: 0 } },
reportDate: { $dateToString: { date: new Date(), format: "%Y-%m-%d" } },
reportBy: "hellouser123",
reportNumber: { $literal: 1 }
}
)
To set the 要将reportRun
field to the value 1
The operation returns the following documents:reportRun
字段设置为值1
,该操作将返回以下文档:
{ "birth" : ISODate("1924-12-03T05:00:00Z"), "contribs" : [ "Fortran", "ALGOL", "Backus-Naur Form", "FP" ], "name" : "John Backus", "awards" : 4, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1927-09-04T04:00:00Z"), "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ], "name" : "John McCarthy", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1906-12-09T05:00:00Z"), "contribs" : [ "UNIVAC", "compiler", "FLOW-MATIC", "COBOL" ], "name" : "Grace Hopper", "awards" : 4, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1926-08-27T04:00:00Z"), "contribs" : [ "OOP", "Simula" ], "name" : "Kristen Nygaard", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1931-10-12T04:00:00Z"), "contribs" : [ "OOP", "Simula" ], "name" : "Ole-Johan Dahl", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1956-01-31T05:00:00Z"), "contribs" : [ "Python" ], "name" : "Guido van Rossum", "awards" : 2, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1941-09-09T04:00:00Z"), "contribs" : [ "UNIX", "C" ], "name" : "Dennis Ritchie", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1965-04-14T04:00:00Z"), "contribs" : [ "Ruby" ], "name" : "Matz Matsumoto", "awards" : 1, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1955-05-19T04:00:00Z"), "contribs" : [ "Java" ], "name" : "James Gosling", "awards" : 2, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "contribs" : [ "Scala" ], "name" : "Martin Odersky", "awards" : 0, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
See also: 另请参阅:
Iterate the Returned Cursor迭代返回的游标
The find()
method returns a cursor to the results.find()
方法向结果返回一个游标。
In 在mongosh
, 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. mongosh
中,如果返回的游标没有使用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
键的变量,如以下部分所示。
With Variable Name带变量名称
The following example uses the variable 以下示例使用变量myCursor
to iterate over the cursor and print the matching documents:myCursor
迭代游标并打印匹配的文档:
var myCursor = db.bios.find( );
myCursor
With next()
Method使用next()
方法
next()
MethodThe following example uses the cursor method 以下示例使用游标方法next()
to access the documents:next()
访问文档:
var myCursor = db.bios.find( );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;
if (myDocument) {
var myName = myDocument.name;
print (tojson(myName));
}
To print, you can also use the 要打印,您也可以使用printjson()
method instead of print(tojson())
:printjson()
方法而不是print(tojson())
:
if (myDocument) {
var myName = myDocument.name;
printjson(myName);
}
With forEach()
Method使用forEach()
方法
forEach()
MethodThe following example uses the cursor method 以下示例使用游标方法forEach()
to iterate the cursor and access the documents:forEach()
来迭代游标并访问文档:
var myCursor = db.bios.find( );
myCursor.forEach(printjson);
Modify the Cursor Behavior修改游标行为
mongosh
and the drivers provide several cursor methods that call on the cursor returned by the find()
method to modify its behavior.mongosh
和驱动程序提供了几个游标方法,这些方法调用find()
方法返回的游标来修改其行为。
Order Documents in the Result Set在结果集中订购文档
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 以下操作返回name
field:bios
集合中按name
字段升序排列的文档:
db.bios.find().sort( { name: 1 } )
sort()
corresponds to the 对应于SQL中的ORDER BY
statement in SQL.ORDER BY
语句。
Limit the Number of Documents to Return限制要返回的文档数量
The limit()
method limits the number of documents in the result set. limit()
方法限制结果集中的文档数。The following operation returns at most 以下操作在5
documents in the bios collection:bios
集合中最多返回5
个文档:
db.bios.find().limit( 5 )
limit()
corresponds to the 对应于SQL中的LIMIT
statement in SQL.LIMIT
语句。
Set the Starting Point of the Result Set设置结果集的起点
The skip()
method controls the starting point of the results set. skip()
方法控制结果集的起点。The following operation skips the first 以下操作将跳过5
documents in the bios collection and returns all remaining documents:bios
集合中的前5
个文档,并返回所有剩余文档:
db.bios.find().skip( 5 )
Specify Collation指定排序规则
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()
操作的排序规则。
db.bios.find( { "name.last": "hopper" } ).collation( { locale: "en_US", strength: 1 } )
Combine Cursor Methods组合游标方法
The following statements chain cursor methods 以下语句链接游标方法limit()
and sort()
:limit()
和sort()
:
db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )
The two statements are equivalent; i.e. the order in which you chain the 这两种说法是等价的;即,limit()
and the sort()
methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on 'name'.limit()
和sort()
方法的连锁顺序并不重要。这两个语句都返回前五个文档,由“name”的升序确定。
Available mongosh
Cursor Methods可用的mongosh
游标方法
mongosh
Cursor MethodsUse Variables in let
Option在let
选项中使用变量
let
OptionYou can specify query options to modify query behavior and indicate how results are returned.您可以指定查询选项来修改查询行为并指示返回结果的方式。
For example, to define variables that you can access elsewhere in the 例如,要定义可以在find
method, use the let
option. find
方法的其他地方访问的变量,请使用let选项。To filter results using a variable, you must access the variable within the 若要使用变量筛选结果,必须访问$expr
operator.$expr
运算符中的变量。
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.find(
{ $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
{ _id: 0 },
{ let : { targetFlavor: "chocolate" }
} )
Output:输出:
[ { flavor: 'chocolate' } ]
Retrieve Documents for Roles Granted to the Current User检索授予当前用户的角色的文档
Starting in MongoDB 7.0, you can use the new 从MongoDB 7.0开始,您可以使用新的USER_ROLES
system variable to return user roles.USER_ROLES
系统变量来返回用户角色。
The scenario in this section shows users with various roles who have limited access to documents in a collection containing budget information.本节中的场景显示了具有各种角色的用户,他们对包含预算信息的集合中的文档的访问权限有限。
The scenario shows one possible use of 该场景显示了USER_ROLES
. USER_ROLES
的一种可能用途。The budget
collection contains documents with a field named allowedRoles
. budget
集合包含一个名为allowedRoles
的字段的文档。As you'll see in the following scenario, you can write queries that compare the user roles found in the 正如您在下面的场景中看到的那样,您可以编写查询,将allowedRoles
field with the roles returned by the USER_ROLES
system variable.allowedRoles
字段中的用户角色与USER_ROLES
系统变量返回的角色进行比较。
For another 有关另一个USER_ROLES
example scenario, see Retrieve Medical Information for Roles Granted to the Current User. That example doesn't store the user roles in the document fields, as is done in the following example.USER_ROLES
示例场景,请参阅检索授予当前用户的角色的医疗信息。该示例不会像下面的示例那样将用户角色存储在文档字段中。
For the budget scenario in this section, perform the following steps to create the roles, users, and 对于本节中的预算方案,请执行以下步骤来创建角色、用户和budget
collection:budget
集合:
Create the users创建用户
Create users named 创建具有所需角色的名为John
and Jane
with the required roles. John
和Jane
的用户。Replace the 将test
database with your database name.test
数据库替换为您的数据库名称。
db.createUser( {
user: "John",
pwd: "jn008",
roles: [
{ role: "Marketing", db: "test" },
{ role: "Development", db: "test" },
{ role: "Operations", db: "test" },
{ role: "read", db: "test" }
]
} )
db.createUser( {
user: "Jane",
pwd: "je009",
roles: [
{ role: "Sales", db: "test" },
{ role: "Operations", db: "test" },
{ role: "read", db: "test" }
]
} )
Create the collection创建集合
Run:运行:
db.budget.insertMany( [
{
_id: 0,
allowedRoles: [ "Marketing" ],
comment: "For marketing team",
yearlyBudget: 15000
},
{
_id: 1,
allowedRoles: [ "Sales" ],
comment: "For sales team",
yearlyBudget: 17000,
salesEventsBudget: 1000
},
{
_id: 2,
allowedRoles: [ "Operations" ],
comment: "For operations team",
yearlyBudget: 19000,
cloudBudget: 12000
},
{
_id: 3,
allowedRoles: [ "Development" ],
comment: "For development team",
yearlyBudget: 27000
}
] )
Perform the following steps to retrieve the documents accessible to 执行以下步骤以检索John
:John
可访问的文档:
Retrieve the documents检索文档
To use a system variable, add 要使用系统变量,请在变量名的开头添加$$
to the start of the variable name. $$
。Specify the 将USER_ROLES
system variable as $$USER_ROLES
.USER_ROLES
系统变量指定为$$USER_ROLES
。
Run:运行:
db.budget.find( {
$expr: {
$not: {
$eq: [ { $setIntersection: [ "$allowedRoles", "$$USER_ROLES.role" ] }, [] ]
}
}
} )
The previous example returns the documents from the 上一个示例返回budget
collection that match at least one of the roles that the user who runs the example has. budget
集合中与运行该示例的用户所具有的至少一个角色相匹配的文档。To do that, the example uses 为此,该示例使用$setIntersection
to return documents where the intersection between the budget
document allowedRoles
field and the set of user roles from $$USER_ROLES
is not empty.$setIntersection
返回budget
(预算)文档allowedRoles
字段和$$user_roles
中的用户角色集之间的交集不为空的文档。
Examine the documents检查文件
John
has the Marketing
, Operations
, and Development
roles, and sees these documents:John
负责Marketing
、Operations
和Development
,并查看以下文档:
[
{
_id: 0,
allowedRoles: [ 'Marketing' ],
comment: 'For marketing team',
yearlyBudget: 15000
},
{
_id: 2,
allowedRoles: [ 'Operations' ],
comment: 'For operations team',
yearlyBudget: 19000,
cloudBudget: 12000
},
{
_id: 3,
allowedRoles: [ 'Development' ],
comment: 'For development team',
yearlyBudget: 27000
}
]
Perform the following steps to retrieve the documents accessible to 执行以下步骤以检索Jane
:Jane
可访问的文档:
Examine the documents检查文件
Jane
has the Sales
and Operations
roles, and sees these documents:Jane
担任Sales
和Operations
角色,并查看以下文档:
[
{
_id: 1,
allowedRoles: [ 'Sales' ],
comment: 'For sales team',
yearlyBudget: 17000,
salesEventsBudget: 1000
},
{
_id: 2,
allowedRoles: [ 'Operations' ],
comment: 'For operations team',
yearlyBudget: 19000,
cloudBudget: 12000
}
]
On a sharded cluster, a query can be run on a shard by another server node on behalf of the user. In those queries, 在分片集群上,另一个服务器节点可以代表用户在分片上运行查询。在这些查询中,USER_ROLES
is still populated with the roles for the user.USER_ROLES
仍然填充有用户的角色。
Learn More了解更多信息
To see all available query options, see FindOptions.要查看所有可用的查询选项,请参阅FindOptions
。