Docs Menu

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 documents
Query 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 using findOne() with an options document, see the example.

If you specify a projection parameter, findOne() returns a document that only contains the projection fields. The _id field is always included unless you explicitly exclude it.

注意

Although similar to the find() method, the findOne() method returns a document rather than a cursor.

このメソッドは、次の環境でホストされている配置で使用できます。

  • MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです

注意

このコマンドは、すべての MongoDB Atlas クラスターでサポートされています。すべてのコマンドに対する Atlas のサポートについては、「サポートされていないコマンド」を参照してください。

  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン

findOne() メソッドの形式は次のとおりです。

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

findOne() メソッドは次のパラメーターを取ります。

Parameter
タイプ
説明

query

ドキュメント

Optional. Specifies query selection criteria using query operators.

projection

ドキュメント

Optional. Specifies the fields to return using projection operators. Omit this parameter to return all fields in the matching document. For details, see プロジェクション.

options

ドキュメント

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:

projection パラメーターにより、一致するドキュメントで返されるフィールドが決定されます。projection パラメーターは以下の形式のドキュメントです。

{ field1: <value>, field2: <value> ... }
プロジェクション
説明

<field>: <1 or true>

フィールドを包含することを指定します。プロジェクションの値としてゼロ以外の整数を指定した場合、その値を true として処理します。

<field>: <0 or false>

フィールドの除外を指定します。

"<field>.$": <1 or true>

$ 配列プロジェクション 演算子を使用して、配列フィールドのクエリ条件に一致する最初の要素を返します。プロジェクションの値としてゼロ以外の整数を指定した場合、その値を true として処理します。

ビューには使用できません。

<field>: <array projection>

配列プロジェクション 演算子($elemMatch$slice)を使用して、含める配列要素を指定します。

ビューには使用できません。

<field>: <$meta expression>

$meta 演算子式を使用して、使用可能な per-document metadataを含めることを指定します。

ビューには使用できません。

<field>: <aggregation expression>

プロジェクションを行ったフィールドの値を指定します。

集計式と構文の使用(リテラルと集計変数の使用を含む)では、新しいフィールドをプロジェクションしたり、既存のフィールドを新しい値でプロジェクションしたりできます。

  • プロジェクションの値として数値でもブール値でもないリテラル(例えば、文字列リテラルや配列、演算子式)を指定すると、フィールドは新しい値でプロジェクションされます。次に例を示します。

    • { field: [ 1, 2, 3, "$someExistingField" ] }

    • { field: "New String Value" }

    • { field: { status: "Active", total: { $sum: "$existingArray" } } }

  • フィールドにリテラル値をプロジェクションするには、$literal 集計式を使用します。次に例を示します。

    • { field: { $literal: 5 } }

    • { field: { $literal: true } }

    • { field: { $literal: { fieldWithValue0: 0, fieldWithValue1: 1 } } }

埋め込みドキュメント内のフィールドの場合は、次のいずれかを使用してフィールドを指定できます。

  • ドット表記の場合は次のようになります。 "field.nestedfield": <value>

  • ネストされた形式、例: { field: { nestedfield: <value> } }

_id フィールドは、プロジェクションで _id: 0 を明示的に指定して抑制しない限り、返されるドキュメントにデフォルトで含まれます。

projection には、 _id フィールドを除いて、包含指定と除外指定の両方を含めることはできません。

  • フィールドを明示的に含めるプロジェクションでは、_id フィールドだけが明示的に除外できる唯一のフィールドです。

  • フィールドを明示的に除外するプロジェクションでは、_id フィールドが明示的に包含できる唯一のフィールドですが、デフォルトで _id フィールドが含まれます。

プロジェクションの詳細については、以下も参照してください。

The following operation returns a single document from the bios collection:

db.bios.findOne()

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') } }
]
}
)

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

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

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

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

クエリオプションを指定してクエリの動作を変更することで、結果が返される方法を指定できます。

たとえば、 findOne メソッド内の他の場所からアクセスできる変数を定義するには、 let オプションを使用します。変数を使用して結果をフィルターするには、$expr 演算子内で変数にアクセスする必要があります。

コレクション cakeFlavors を以下ように作成します。

db.cakeFlavors.insertMany( [
{ _id: 1, flavor: "chocolate" },
{ _id: 2, flavor: "strawberry" },
{ _id: 3, flavor: "cherry" }
] )

次の例では、lettargetFlavor 変数を定義し、その変数を使用してチョコレート ケーキの風味を検索します。

db.cakeFlavors.findOne(
{ $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
{ _id: 0 },
{ let : { targetFlavor: "chocolate" }
} )

出力:

{ flavor: 'chocolate' }

To see all available query options, see FindOptions.