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结果0 Any任意The method returns该方法返回nullnull1 Any任意The method returns the document that satisfies the specified query criteria.该方法返回满足指定查询条件的文档。2 or more Collection 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 more Index 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如果用例要求一致选择特定记录,则必须使用optionsdocument to specify a sort.options文档指定排序。For details on using有关在findOne()with anoptionsdocument, see the example.options文档中使用findOne()的详细信息,请参阅示例。If you specify a如果指定projectionparameter,findOne()returns a document that only contains theprojectionfields.projection参数,findOne()将返回仅包含projection字段的文档。The_idfield is always included unless you explicitly exclude it._id字段始终包含在内,除非您明确排除它。
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()方法接受以下参数:
query | ||
projection | ||
options | 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阶段一致的一部分:
Thefind()andfindAndModify()projection can accept aggregation expressions and syntax.find()和findAndModify()投影可以接受聚合表达式和语法。MongoDB enforces additional restrictions with regards to projections. See Projection Restrictions for details.MongoDB对预测实施了额外的限制。有关详细信息,请参阅投影限制。
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> |
|
<field>: <array projection> |
|
<field>: <$meta expression> |
|
<field>: <aggregation expression> |
|
Note
You can specify projection in two ways for 您可以通过两种方式为find() and findOne():find()和findOne()指定投影:
Setting the设置projectionparameterprojection参数Setting the将optionsparameter toprojectionoptions参数设置为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参数设置为null或undefined。
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在显式纳入字段的投影中,_idfield is the only field that you can explicitly exclude._id字段是唯一可以显式排除的字段。In projections that explicitly excludes fields, the在明确排除字段的投影中,_idfield is the only field that you can explicitly include; however, the_idfield 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 以下操作在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嵌入文档中的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结果文档
findOne Result DocumentYou 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 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。