AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

1 つのフィールドでのインデックスの作成

1 つのフィールドにインデックスを作成すると、そのフィールドに対するクエリのパフォーマンスを向上させることができます。

単一フィールドインデックスを作成するには、db.collection.createIndex() メソッドを使用します。

db.<collection>.createIndex( { <field>: <sort-order> } )

次のドキュメントを含むstudentsコレクションを作成します。

db.students.insertMany( [
{
"name": "Alice",
"gpa": 3.6,
"location": { city: "Sacramento", state: "California" }
},
{
"name": "Bob",
"gpa": 3.2,
"location": { city: "Albany", state: "New York" }
}
] )

次の例は、次の方法を示しています。

GPA で学生を頻繁に検索する学校の管理者を考えてみましょう。 gpaフィールドにインデックスを作成すると、これらのクエリのパフォーマンスが向上します。

db.students.createIndex( { gpa: 1 } )

インデックスは、次のようなフィールドgpaを選択するクエリをサポートしています。

db.students.find( { gpa: 3.6 } )
db.students.find( { gpa: { $lt: 3.4 } } )

埋め込みドキュメント内のフィールドにインデックスを作成できます。 埋め込みフィールドのインデックスは、ドット表記を使用するクエリを実行できます。

location フィールドは、埋め込みフィールド citystateを含む埋め込みドキュメントです。location.state フィールドにインデックスを作成します。

db.students.createIndex( { "location.state": 1 } )

インデックスは、次のようなフィールドlocation.stateのクエリをサポートします。

db.students.find( { "location.state": "California" } )
db.students.find( { "location.city": "Albany", "location.state": "New York" } )