Database Manual / Reference / mongosh Methods / Collections

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

Definition定义

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

Returns one document that satisfies the specified query criteria on the collection or view.返回一个满足集合或视图上指定查询条件的文档。

The returned document may vary depending on the number of documents that match the query criteria, and the query plan used:返回的文档可能因符合查询条件的文档数量和使用的查询计划而异:

Number of matching documents匹配的文档数量Query plan查询计划Result结果
0Any任意The method returns null该方法返回null
1Any任意The method returns the document that satisfies the specified query criteria.该方法返回满足指定查询条件的文档。
2 or moreCollection Scan集合扫描The method returns the first document according to the natural order. In capped collections, natural order is the same as insertion order.该方法根据自然顺序返回第一个文档。在封顶集合中,自然顺序与插入顺序相同。
2 or moreIndex Scan索引扫描The method returns the first document retrieved from the index.该方法返回从索引中检索到的第一个文档。

Important

If the query plan changes to use a different index, the method may return a different document. 如果查询计划更改为使用不同的索引,则该方法可能会返回不同的文档。If your use case requires that a particular record is chosen consistently, you must use the options document to specify a sort. 如果用例要求一致选择特定记录,则必须使用options文档指定排序。For details on using findOne() with an options document, see the example.有关在options文档中使用findOne()的详细信息,请参阅示例

If you specify a projection parameter, findOne() returns a document that only contains the projection fields. 如果指定projection参数,findOne()将返回仅包含projection字段的文档。The _id field is always included unless you explicitly exclude it._id字段始终包含在内,除非您明确排除它。

Note

Although similar to the find() method, the findOne() method returns a document rather than a cursor.虽然类似于find()方法,但findOne()方法返回的是文档而不是游标。

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

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

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

Parameter参数Type类型Description描述
querydocument文档Optional. 可选。Specifies query selection criteria using query operators.使用查询运算符指定查询选择条件。
projectiondocument文档Optional. 可选。Specifies the fields to return using projection operators. 使用投影运算符指定要返回的字段。Omit this parameter to return all fields in the matching document. For details, see Projection.省略此参数以返回匹配文档中的所有字段。有关详细信息,请参阅投影
optionsdocument文档Optional. 可选。Specifies additional options for the query. These options modify query behavior and how results are returned. 指定查询的其他选项。这些选项修改查询行为和返回结果的方式。To see available options, see FindOptions.要查看可用选项,请参阅FindOptions

Behavior行为

Client Disconnection客户端断开连接

If the client that issued db.collection.findOne() disconnects before the operation completes, MongoDB marks db.collection.findOne() for termination using killOp.如果发出db.collection.findOne()的客户端在操作完成之前断开连接,MongoDB将使用killOp标记db.collection.findOne()以终止。

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参数决定了在匹配文档中返回哪些字段。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 } } }

Note

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. 如果同时指定这两个参数,则projection参数优先。To use options.projection, set the projection parameter to null or undefined.要使用options.projection,请将projection参数设置为nullundefined

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

_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:投影不能同时包含纳入式规范和排除式规范,_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字段。

For more information on projection, see also:有关投影的更多信息,请参阅:

Examples示例

With Empty Query Specification使用空查询规范

The following operation returns a single document from the bios collection:以下操作从bios集合返回单个文档:

db.bios.findOne()

With a Query Specification使用查询规范

The following operation returns the first matching document from the bios collection where either the field first in the embedded document name starts with the letter G or where the field birth is less than new Date('01/01/1945'):以下操作返回bios集合中的第一个匹配文档,其中嵌入文档name中的first字段以字母G开头,或者字段birth小于new Date('01/01/1945')

db.bios.findOne(
{
$or: [
{ 'name.first' : /^G/ },
{ birth: { $lt: new Date('01/01/1945') } }
]
}
)

With a Projection带投影

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.projection参数指定要返回哪些字段。该参数包含纳入或排除规范,而不是两者都包含,除非排除是针对_id字段的。

Specify the Fields to Return指定要返回的字段

The following operation finds a document in the bios collection and returns only the name, contribs and _id fields:以下操作在bios集合中查找文档,并仅返回namecontribs_id字段:

db.bios.findOne(
{ },
{ name: 1, contribs: 1 }
)

Return All but the Excluded Fields返回除排除字段外的所有字段

The following operation returns a document in the bios collection where the contribs field contains the element OOP and returns all fields except the _id field, the first field in the name embedded document, and the birth field:以下操作返回bios集合中的一个文档,其中contribs字段包含元素OOP,并返回除_id字段、name嵌入文档中的first字段和birth字段之外的所有字段:

db.bios.findOne(
{ contribs: 'OOP' },
{ _id: 0, 'name.first': 0, birth: 0 }
)

With an Option有一个选项

The following operation uses the sort option to return the first matching document from the sorted bios collection. In this example, the collection is sorted by birth in ascending order.以下操作使用sort选项从已排序的bios集合中返回第一个匹配的文档。在这个例子中,集合按birth顺序升序排列。

db.bios.findOne(
{ },
{ },
{ sort: { birth: 1 } }
)

The findOne Result DocumentfindOne结果文档

You cannot apply cursor methods to the result of findOne() because a single document is returned. You have access to the document directly:您不能将游标方法应用于findOne()的结果,因为返回的是单个文档。您可以直接访问该文档:

var myDocument = db.bios.findOne();

if (myDocument) {
var myName = myDocument.name;

print (tojson(myName));
}

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 findOne method, use the let option. 例如,要定义可以在findOne方法的其他地方访问的变量,请使用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.findOne(
{ $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
{ _id: 0 },
{ let : { targetFlavor: "chocolate" }
} )

Output:输出:

{ flavor: 'chocolate' }

To see all available query options, see FindOptions.要查看所有可用的查询选项,请参阅FindOptions