db.collection.findOne()
On this page本页内容
Definition定义
db.collection.findOne(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.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: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.有关详细信息,请参阅投影。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:返回值: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 theprojection
fields.projection
参数,findOne()
将返回一个仅包含projection
字段的文档。The_id
field is always included unless you explicitly exclude it._id
字段始终包含在内,除非您明确排除它。Although similar to the尽管与find()
method, thefindOne()
method returns a document rather than a cursor.find()
方法类似,findOne()
方法返回的是文档而不是游标。
Behavior行为
Client Disconnection客户端断开连接
Starting in MongoDB 4.2, if the client that issued 从MongoDB 4.2开始,如果发出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投影
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. The projection
parameter takes a document of the following form:projection
参数确定在匹配的文档中返回哪些字段。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)(从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
字段在默认情况下是包含在内的。
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
集合中的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 参数包含include或exclude规范,而不是两者都包含,除非exclude用于_id
field._id
字段。
Specify the Fields to Return指定要返回的字段
The following operation finds a document in the bios collection and returns only the 以下操作在bios集合中查找文档,并仅返回name
, contribs
and _id
fields:name
、contribs
和_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
嵌入文档中的第一个字段和birth
字段之外的所有字段:
db.bios.findOne(
{ contribs: 'OOP' },
{ _id: 0, 'name.first': 0, birth: 0 }
)
The findOne
Result DocumentfindOne
结果文档
findOne
Result DocumentYou 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));
}
Use 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 例如,要定义可以在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
。