db.collection.findOne()
MongoDB とドライバー
このページではmongosh
メソッドがドキュメントされています。 MongoDB ドライバーで同等のメソッドを確認するには、プログラミング言語の対応するページを参照してください。
定義
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 クエリプラン used:
Number of matching documentsQuery plan結果0
Any
The method returns
null
1
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 自然な順序. 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.
重要
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. For details on usingfindOne()
with anoptions
document, see the example.If you specify a
projection
parameter,findOne()
returns a document that only contains theprojection
fields. The_id
field is always included unless you explicitly exclude it.
互換性
このメソッドは、次の環境でホストされている配置で使用できます。
MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
注意
このコマンドは、すべての MongoDB Atlas クラスターでサポートされています。すべてのコマンドに対する Atlas のサポートについては、「サポートされていないコマンド」を参照してください。
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
findOne()
メソッドの形式は次のとおりです。
db.collection.findOne( <query>, <projection>, <options> )
findOne()
メソッドは次のパラメーターを取ります。
Parameter | タイプ | 説明 |
---|---|---|
| ドキュメント | Optional. Specifies query selection criteria using query operators. |
| ドキュメント | Optional. Specifies the fields to return using projection operators. Omit this parameter to return all fields in the matching document. For details, see プロジェクション. |
| ドキュメント | Optional. Specifies additional options for the query. These options modify query behavior and how results are returned. To see available options, see FindOptions. |
動作
クライアントの切断
MongoDB 4.2以降では、 db.collection.findOne()
を発行したクライアントが操作の完了前に切断した場合、MongoDB は killOp
を使用して
db.collection.findOne()
を終了対象としてマークし 。
プロジェクション
重要
言語の整合性
As part of making find()
and
findAndModify()
projection consistent with
aggregation's $project
stage:
find()
とfindAndModify()
のプロジェクションは集計式と構文 を受け付けます。MongoDB は、プロジェクションに関して追加の制限を適用します。詳細については、「プロジェクションの制限」を参照してください。
projection
パラメーターにより、一致するドキュメントで返されるフィールドが決定されます。projection
パラメーターは以下の形式のドキュメントです。
{ field1: <value>, field2: <value> ... }
プロジェクション | 説明 |
---|---|
| フィールドを包含することを指定します。プロジェクションの値としてゼロ以外の整数を指定した場合、その値を |
| フィールドの除外を指定します。 |
| |
| 配列プロジェクション 演算子( ビューには使用できません。 |
|
ビューには使用できません。 |
| プロジェクションを行ったフィールドの値を指定します。 集計式と構文の使用(リテラルと集計変数の使用を含む)では、新しいフィールドをプロジェクションしたり、既存のフィールドを新しい値でプロジェクションしたりできます。
|
埋め込みフィールド仕様
埋め込みドキュメント内のフィールドの場合は、次のいずれかを使用してフィールドを指定できます。
ドット表記の場合は次のようになります。
"field.nestedfield": <value>
ネストされた形式、例:
{ field: { nestedfield: <value> } }
_id
フィールドプロジェクション
_id
フィールドは、プロジェクションで _id: 0
を明示的に指定して抑制しない限り、返されるドキュメントにデフォルトで含まれます。
包含または除外
projection
には、 _id
フィールドを除いて、包含指定と除外指定の両方を含めることはできません。
フィールドを明示的に含めるプロジェクションでは、
_id
フィールドだけが明示的に除外できる唯一のフィールドです。フィールドを明示的に除外するプロジェクションでは、
_id
フィールドが明示的に包含できる唯一のフィールドですが、デフォルトで_id
フィールドが含まれます。
プロジェクションの詳細については、以下も参照してください。
例
With Empty Query Specification
The following operation returns a single document from the bios collection:
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')
:
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.
返却するフィールドの指定
The following operation finds a document in the bios collection and
returns only the name
, contribs
and _id
fields:
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:
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.
db.bios.findOne( { }, { }, { sort: { birth: 1 } } )
The findOne
Result Document
You cannot apply cursor methods to the result of
findOne()
because a single document is
returned. You have access to the document directly:
var myDocument = db.bios.findOne(); if (myDocument) { var myName = myDocument.name; print (tojson(myName)); }
let
オプションでの変数の使用
クエリオプションを指定してクエリの動作を変更することで、結果が返される方法を指定できます。
たとえば、 findOne
メソッド内の他の場所からアクセスできる変数を定義するには、 let
オプションを使用します。変数を使用して結果をフィルターするには、$expr
演算子内で変数にアクセスする必要があります。
コレクション cakeFlavors
を以下ように作成します。
db.cakeFlavors.insertMany( [ { _id: 1, flavor: "chocolate" }, { _id: 2, flavor: "strawberry" }, { _id: 3, flavor: "cherry" } ] )
次の例では、let
で targetFlavor
変数を定義し、その変数を使用してチョコレート ケーキの風味を検索します。
db.cakeFlavors.findOne( { $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } }, { _id: 0 }, { let : { targetFlavor: "chocolate" } } )
出力:
{ flavor: 'chocolate' }
To see all available query options, see FindOptions.