Database Manual / Reference / mongosh Methods / Collections

db.collection.find() (mongosh method方法)

Definition定义

db.collection.find(query, projection, options)

Selects documents in a collection or view and returns a cursor to the selected documents.选择集合或视图中的文档,并将游标返回到所选文档。

Returns:返回A cursor to the documents that match the query criteria. 指向符合查询条件的文档的游标When the find() method "returns documents," the method is actually returning a cursor to the documents.find()方法“返回文档”时,该方法实际上是将游标返回到文档。

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令

  • 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() method has the following form:find()方法具有以下形式:

db.collection.find( <query>, <projection>, <options> )

The find() method takes the following parameters:find()方法接受以下参数:

Parameter参数Type类型Description描述
querydocument文档

Optional. 可选。Specifies selection filter using query operators. 使用查询运算符指定选择筛选器。To return all documents in a collection, omit this parameter or pass an empty document ({}).若要返回集合中的所有文档,请省略此参数或传递一个空文档({})。

projectiondocument文档

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.指定要在与查询筛选器匹配的文档中返回的字段。要返回匹配文档中的所有字段,请省略此参数。有关详细信息,请参阅投影

optionsdocument文档

Optional. 可选。Specifies additional options for the query. These options modify query behavior and how results are returned. For details, see Options.指定查询的其他选项。这些选项修改查询行为和返回结果的方式。有关详细信息,请参阅选项

Behavior行为

Projection投影

Important

Language Consistency语言一致性

As part of making find() and findAndModify() projection consistent with aggregation's $project stage,作为使find()findAndModify()投影与聚合的$project阶段一致的一部分,

The projection parameter determines which fields are returned in the matching documents. The projection parameter takes a document of the following form:projection参数决定了在匹配文档中返回哪些字段。投影参数采用以下形式的文档:

{ <field1>: <value>, <field2>: <value> ... }
Projection投影Description描述
<field>: <1 or true>Specifies the inclusion of a field. If you specify a non-zero integer for the projection value, the operation treats the value as true.指定是否包含字段。如果为投影值指定非零整数,则操作会将该值视为true
<field>: <0 or false>Specifies the exclusion of a field.指定排除字段。
"<field>.$": <1 or true>

Uses the $ array projection operator to return the first element that matches the query condition on the array field. 使用$数组投影运算符返回与数组字段上的查询条件匹配的第一个元素。If you specify a non-zero integer for the projection value, the operation treats the value as true.如果为投影值指定非零整数,则操作会将该值视为true

Not available for views.视图不可用。

<field>: <array projection>

Uses the array projection operators ($elemMatch, $slice) to specify the array elements to include.使用数组投影运算符($elemMatch$slice)指定要包含的数组元素。

Not available for views.视图不可用。

<field>: <$meta expression>

Uses the $meta operator expression to specify the inclusion of available per-document metadata.使用$meta运算符表达式指定包含可用的每个文档元数据

Not available for views.视图不可用。

<field>: <aggregation expression>

Specifies the value of the projected field.指定投影字段的值。

With the use of aggregation expressions and syntax, including the use of literals and aggregation variables, you can project new fields or project existing fields with new values.通过使用聚合表达式和语法,包括使用文字和聚合变量,您可以投影新字段或用新值投影现有字段。

  • If you specify a non-numeric, non-boolean literal (such as a literal string or an array or an operator expression) for the projection value, the field is projected with the new value, for example:如果为投影值指定非数字、非布尔文字(如文字字符串、数组或运算符表达式),则字段将用新值投影,例如:

    • { field: [ 1, 2, 3, "$someExistingField" ] }
    • { field: "New String Value" }
    • { field: { status: "Active", total: { $sum: "$existingArray" } } }
  • To project a literal value for a field, use the $literal aggregation expression; for example:要为字段投影文字值,请使用$literal聚合表达式;例如:

    • { field: { $literal: 5 } }
    • { field: { $literal: true } }
    • { field: { $literal: { fieldWithValue0: 0, fieldWithValue1: 1 } } }

Options选项

Option选项Description描述
allowDiskUseWhether or not pipelines that require more than 100 megabytes of memory to execute write to temporary files on disk. For details, see cursor.allowDiskUse().是否需要超过100兆字节内存来执行对磁盘上临时文件的写入的管道。有关详细信息,请参阅cursor.allowDiskUse()
allowPartialResultsFor queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable.对于针对分片集合的查询,如果一个或多个查询的分片不可用,则允许命令(或后续的getMore命令)返回部分结果,而不是错误。
awaitDataIf the cursor is a a tailable-await cursor. Requires tailable to be true.如果游标是可尾随的等待游标。需要tailabletrue
collationCollation settings for update operation.更新操作的排序规则设置。
commentAdds a $comment to the query that shows in the profiler logs.分析器日志中显示的查询添加$comment
explainAdds explain output based on the verbosity mode provided.根据提供的详细程度模式添加解释输出。
hintForces the query optimizer to use specific indexes in the query.强制查询优化器在查询中使用特定索引。
limitSets a limit of documents returned in the result set.设置结果集中返回的文档数量限制。
maxThe exclusive upper bound for a specific index.特定指数的唯一上限。
maxAwaitTimeMSThe maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires tailable and awaitData to be true.服务器等待新文档以满足可跟踪游标查询的最长时间。需要tailableawaitDatatrue
maxTimeMSThe maximum amount of time (in milliseconds) the server should allow the query to run.服务器应允许查询运行的最长时间(以毫秒为单位)。
minThe inclusive lower bound for a specific index.特定指数的包容性下限。
noCursorTimeoutWhether the server should timeout the cursor after a period of inactivity (by default 10 minutes).服务器是否应在一段时间不活动后(默认为10分钟)超时游标。
projection

Specifies the fields to return in the documents that match the query filter.指定要在与查询筛选器匹配的文档中返回的字段。

You can specify projection in two ways for find() and findOne():您可以通过两种方式为find()findOne()指定投影:

  • Setting the projection parameter设置projection参数
  • Setting the options parameter to projectionoptions参数设置为projection

If you specify both parameters, the projection parameter takes precedence. To use options.projection, set the projection parameter to null or undefined.如果同时指定这两个参数,则projection参数优先。要使用options.projection,请将projection参数设置为nullundefined

readConcernSpecifies the read concern level for the query.指定查询的读取关注级别。
readPreferenceSpecifies the read preference level for the query.指定查询的读取首选项级别。
returnKeyWhether only the index keys are returned for a query.是否只返回查询的索引键。
showRecordIdIf the $recordId field is added to the returned documents. 如果返回的文档中添加了$recordId字段。The $recordId indicates the position of the document in the result set.$recordId表示文档在结果集中的位置。
skipHow many documents to skip before returning the first document in the result set.返回结果集中的第一个文档之前要跳过多少个文档。
sortThe order of the documents returned in the result set. Fields specified in the sort, must have an index.结果集中返回的文档的顺序。排序中指定的字段必须有索引。
tailableIndicates if the cursor is tailable. Tailable cursors remain open after the intial results of the query are exhausted. 指示游标是否可尾随。可定制游标在查询的初始结果用尽后仍保持打开状态。Tailable cursors are only available on Capped Collections.可定制游标仅在封顶集合上可用。

Embedded Field Specification嵌入式现场规范

For fields in an embedded documents, you can specify the field using either:对于嵌入文档中的字段,您可以使用以下任一方式指定字段:

  • dot notation, for example "field.nestedfield": <value>点符号,例如"field.nestedfield": <value>
  • nested form, for example 嵌套形式,例如{ field: { nestedfield: <value> } }

_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不能同时包含纳入式规范和排除式规范,_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. For instance, numeric types undergo conversion before comparison. 为了便于比较,MongoDB将某些数据类型视为等效的。例如,数字类型在比较之前会进行转换。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. Consider the following collection:但是,对于大多数数据类型,比较运算符仅对目标字段的BSON类型与查询操作数类型匹配的文档执行比较。考虑以下集合:

{ "_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操作数是整数类型。

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.要在集合中强制执行数据类型,请使用架构验证

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 mongosh associate all operations with a server session, with the exception of unacknowledged write operations. MongoDB驱动程序和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 may be idle for longer than 30 minutes, associate the operation with an explicit session using Mongo.startSession() and periodically refresh the session using the refreshSessions command. 对于可能空闲超过30分钟的操作,请使用Mongo.startSession()将该操作与显式会话相关联,并使用refreshSessions命令定期刷新会话。See Session Idle Timeout for more information.有关更多信息,请参阅会话空闲超时

Transactions事务

db.collection.find() can be used inside distributed 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

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 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()以终止。

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.您可以为finddistinctaggregate命令添加查询设置。

Query settings have more functionality and are preferred over deprecated index filters.查询设置具有更多功能,并且优于已弃用的索引筛选器

To remove query settings, use removeQuerySettings. 要删除查询设置,请使用removeQuerySettingsTo obtain the query settings, use a $querySettings stage in an aggregation pipeline.要获取查询设置,请在聚合管道中使用$querySettings阶段。

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 equals 5:以下操作返回bios集合_id等于5的文档:

    db.bios.find( { _id: 5 } )
  • The following operation returns documents in the bios collection where the field last in the name embedded document equals "Hopper":以下操作返回bios集合中的文档,其中嵌入文档name中的last字段等于"Hopper"

    db.bios.find( { "name.last": "Hopper" } )

    Note

    To 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 either 5 or ObjectId("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 the bios collection where birth is greater than new 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 where name.last field starts with the letter N (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 Predicates.有关查询运算符的列表,请参阅查询谓词

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):以下操作从birthnew Date('1940-01-01')new Date('1960-01-01')之间的bios集合文档返回(不包括在内):

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 Predicates.有关查询运算符的列表,请参阅查询谓词

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 Predicates.有关查询运算符的列表,请参阅查询谓词

Compare Two Fields from A Single Document比较单个文档中的两个字段

$expr can contain expressions that compare fields from the same document.可以包含比较同一文档中字段的表达式。

Create a monthlyBudget collection with these documents:使用以下文档创建monthlyBudget(月度预算)集合:

db.monthlyBudget.insertMany( [
{ _id : 1, category : "food", budget : 400, spent : 450 },
{ _id : 2, category : "drinks", budget : 100, spent : 150 },
{ _id : 3, category : "clothes", budget : 100, spent : 50 },
{ _id : 4, category : "misc", budget : 500, spent : 300 },
{ _id : 5, category : "travel", budget : 200, spent : 650 }
] )

The following operation uses $expr to find documents where the spent amount exceeds the budget:以下操作使用$expr查找spent(支出)金额超过budget(预算)的文档:

db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )

Output:输出:

{ _id : 1, category : "food", budget : 400, spent : 450 }
{ _id : 2, category : "drinks", budget : 100, spent : 150 }
{ _id : 5, category : "travel", budget : 200, spent : 650 }

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. The query does not match documents with the following name fields:name字段必须与嵌入的文档完全匹配。查询与具有以下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 field contribs 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 of contribs 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 Predicate Operators.数组查询谓词运算符。

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 with award 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 the award field equals "Turing Award" and the year field greater than 1980:以下操作返回bios集合中的文档,其中奖励award(数组)至少包含一个元素,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 Query Predicate Operators.有关特定于数组的查询运算符的列表,请参阅数组查询谓词运算符

Query for BSON Regular Expressions查询BSON正则表达式

To find documents that contain BSON regular expressions as values, call find() with the bsonRegExp option set to true. The bsonRegExp option allows you to return regular expressions that can't be represented as JavaScript regular expressions.要查找包含BSON正则表达式作为值的文档,请在bsonRegExp选项设置为true的情况下调用find()bsonRegExp选项允许您返回不能表示为JavaScript正则表达式的正则表达式。

The following operation returns documents in a collection named testbson where the value of a field named foo is a BSONRegExp type:以下操作返回名为testbson的集合中的文档,其中名为foo的字段的值是BSONRegExp类型:

db.testbson.find( {}, {}, { bsonRegExp: true } )
[
{
_id: ObjectId('65e8ba8a4b3c33a76e6cacca'),
foo: BSONRegExp('(?-i)AA_', 'i')
}
]

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 _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字段。

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 } )

Note

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字段

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 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 } } )

You can also specify embedded fields using the nested form. For example:您还可以使用嵌套表单指定嵌入字段。例如:

db.bios.find(
{ },
{ _id: 0, name: { last: 1 }, contribs: { $slice: 2 } }
)

Use Aggregation Expression使用聚合表达式

db.collection.find() projection can accept aggregation expressions and syntax.投影可以接受聚合表达式和语法

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.例如,以下操作使用聚合表达式覆盖nameawards字段的值,并包含新字段reportDatereportByreportNumber

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 }

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 update the displayBatchSize variable to change the number of automatically iterated documents.您可以更新displayBatchSize变量以更改自动迭代文档的数量。

The following example sets the batch size to 3. Future db.collection.find() operations will only return 3 documents per cursor iteration.以下示例将批大小设置为3。未来的db.collection.find()操作每次游标迭代只会返回3个文档。

config.set( "displayBatchSize", 3 )

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()方法

The 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()方法

The 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 ORDER BY statement in SQL.sort()对应于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 LIMIT statement in SQL.对应于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. 这两个陈述是等价的;也就是说,你链接limit()sort()方法的顺序并不重要。Both statements return the first five documents, as determined by the ascending sort order on 'name'.这两个语句都返回前五个文档,由“name”的升序排序决定。

Available mongosh Cursor Methods可用的mongosh游标方法

Use Variables in let Optionlet选项中使用变量

You 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 USER_ROLES system variable to return user roles.从MongoDB 7.0开始,您可以使用新的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系统变量返回的角色进行比较。

Note

For another USER_ROLES example scenario, see Retrieve Medical Information for Roles Granted to the Current User. 有关另一个USER_ROLES示例场景,请参阅检索授予当前用户的角色的医疗信息That example doesn't store the user roles in the document fields, as is done in the following example.该示例不将用户角色存储在文档字段中,如下例所示。

For the budget scenario in this section, perform the following steps to create the roles, users, and budget collection:对于本节中的预算场景,执行以下步骤以创建角色、用户和budget集合:

1

Create the roles创建角色

Run:运行:

db.createRole( { role: "Marketing", roles: [], privileges: [] } )
db.createRole( { role: "Sales", roles: [], privileges: [] } )
db.createRole( { role: "Development", roles: [], privileges: [] } )
db.createRole( { role: "Operations", roles: [], privileges: [] } )
2

Create the users创建用户

Create users named John and Jane with the required roles. Replace the test database with your database name.创建具有所需角色的名为JohnJane的用户。用数据库名称替换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" }
]
} )
3

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可访问的文档:

1

Log in as John以John的身份登录

Run:运行:

db.auth( "John", "jn008" )
2

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中的用户角色集之间的交集不为空的文档。

3

Examine the documents检查文件

John has the Marketing, Operations, and Development roles, and sees these documents:John担任MarketingOperationsDevelopment职位,并查看以下文档:

[
{
_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可访问的文档:

1

Log in as Jane以Jane身份登录

Run:运行:

db.auth( "Jane", "je009" )
2

Retrieve the documents检索文件

Run:运行:

db.budget.find( {
$expr: {
$not: {
$eq: [ { $setIntersection: [ "$allowedRoles", "$$USER_ROLES.role" ] }, [] ]
}
}
} )
3

Examine the documents检查文件

Jane has the Sales and Operations roles, and sees these documents:Jane担任SalesOperations角色,并查看以下文档:

[
{
_id: 1,
allowedRoles: [ 'Sales' ],
comment: 'For sales team',
yearlyBudget: 17000,
salesEventsBudget: 1000
},
{
_id: 2,
allowedRoles: [ 'Operations' ],
comment: 'For operations team',
yearlyBudget: 19000,
cloudBudget: 12000
}
]

Note

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仍然填充有用户的角色。

Modify a Query with options使用选项修改查询

The following examples show how you can use the options field in a find() query. Use the following insertMany() to setup the users collection:以下示例显示了如何在find()查询中使用options字段。使用以下insertMany()来设置users集合:

db.users.insertMany( [
{ username: "david", age: 27 },
{ username: "amanda", age: 25 },
{ username: "rajiv", age: 32 },
{ username: "rajiv", age: 90 }
] )

limit with options限制选项

The following query limits the number of documents in the result set with the limit options parameter:以下查询使用limit选项参数限制结果集中的文档数量:

db.users.find(
{ username : "rajiv"}, // query
{ age : 1 }, // projection
{ limit : 1 } // options
)

allowDiskUse with options选项中有allowDisk

The following query uses the options parameter to enable allowDiskUse:以下查询使用options参数启用allowDiskUse

db.users.find(
{ username : "david" },
{ age : 1 },
{ allowDiskUse : true }
)

explain with options选项中有explain

The following query uses the options parameter to get the executionStats explain output:以下查询使用options参数获取executionStats解释输出:

var cursor = db.users.find(
{ username: "amanda" },
{ age : 1 },
{ explain : "executionStats" }
)
cursor.next()

Specify Multiple options in a query在查询中指定多个选项

The following query uses multiple options in a single query. 以下查询在单个查询中使用多个optionsThis query uses limit set to 2 to return only two documents, and showRecordId set to true to return the position of the document in the result set:此查询将limit设置为2仅返回两个文档,并将showRecordId设置为true的返回文档在结果集中的位置:

db.users.find(
{},
{ username: 1, age: 1 },
{
limit: 2,
showRecordId: true
}
)

Learn More了解更多