db.collection.findOne()

On this page本页内容

Definition定义

db.collection.findOne(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驱动程序文档。

Returns one document that satisfies the specified query criteria on the collection or view. 返回一个满足集合或视图上指定查询条件的文档。If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk. 如果多个文档满足查询,该方法将根据反映磁盘上文档顺序的自然顺序返回第一个文档。In capped collections, natural order is the same as insertion order. If no document satisfies the query, the method returns null.封顶集合中,自然顺序与插入顺序相同。如果没有满足查询的文档,该方法将返回null

Parameter参数Type类型Description描述
query document Optional.可选。Specifies query selection criteria using query operators.使用查询运算符指定查询选择条件。
projection document Optional.可选。Specifies the fields to return using projection operators. 指定要使用投影运算符返回的字段。Omit this parameter to return all fields in the matching document. 省略此参数可返回匹配文档中的所有字段。For details, see Projection.有关详细信息,请参阅投影
Returns:One document that satisfies the criteria specified as the first argument to this method. 满足此方法第一个参数所指定标准的一个文档。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字段,否则它始终包含在内。

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

Behavior行为

Client Disconnection客户端断开

Starting in MongoDB 4.2, if the client that issued the db.collection.findOne() disconnects before the operation completes, MongoDB marks the db.collection.findOne() for termination (i.e. killOp on the operation).从MongoDB 4.2开始,如果发出db.collection.findOne()的客户端在操作完成之前断开连接,MongoDB会将db.collection.findOne()标记为终止(即,操作上的killOp)。

Projection投影

Language Consistency语言一致性

Starting in MongoDB 4.4, as part of making find and findAndModify projection consistent with aggregation’s $project stage,从MongoDB 4.4开始,作为使findfindAndModify投影与聚合的$project阶段保持一致的一部分,

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> ... }
Projection预测Description描述
<field>: <1 or true> Specifies the inclusion of a field.指定字段的包含。
<field>: <0 or false> Specifies the exclusion of a field.指定字段的排除。
"<field>.$": <1 or true> With the use of the $ 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(Not available for views.)(不适用于视图。)
<field>: <array projection> Using the array projection operators $elemMatch, $slice, specifies the array element(s) to include, thereby excluding those elements that do not meet the expressions. 使用数组投影运算符$elemMatch$slice,指定要包含的数组元素,从而排除那些不符合表达式的元素。(Not available for views.)(不适用于视图。)
<field>: <$meta expression> Using the $meta operator expression, specifies the inclusion of available per-document metadata. 使用$meta运算符表达式,指定包含每个文档可用的元数据。(Not available for views.)(不适用于视图。)
<field>: <aggregation expression>

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

Starting in MongoDB 4.4, 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. 从MongoDB 4.4开始,通过使用聚合表达式和语法,包括使用文字和聚合变量,可以投影新字段或使用新值投影现有字段。For example,例如

  • 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; e.g.:如果为投影值指定非数字、非布尔文字(例如文字字符串、数组或运算符表达式),则会使用新值投影字段;如:
    • { 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; e.g.:要为字段投影文字值,请使用$literal聚合表达式;如。:
    • { field: { $literal: 5 } }
    • { field: { $literal: true } }
    • { field: { $literal: { fieldWithValue0: 0, fieldWithValue1: 1 } } }

In versions 4.2 and earlier, any specification value (with the exception of the previously unsupported document value) is treated as either true or false to indicate the inclusion or exclusion of the field.在版本4.2和更早版本中,任何规范值(以前不支持的文档值除外)都被视为truefalse,以指示包含或排除该字段。

New in version 4.4.版本4.4中的新功能。

Embedded Field Specification嵌入式字段规范

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

  • dot notation; e.g. 点符号;如:"field.nestedfield": <value>
  • nested form; e.g. 嵌套形式;如:{ field: { nestedfield: <value> } } (Starting in 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不能同时包含包含和排除规范,但_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. projection参数指定要返回的字段。The parameter contains either include or exclude specifications, not both, unless the exclude is for the _id field.参数包含包含或排除规范,而不是两者,除非排除是针对_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 }
)

The findOne Result DocumentfindOne结果文档

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

var myDocument = db.bios.findOne();

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

   print (tojson(myName));
}