Overview
このガイドでは、読み取り操作を使用して MongoDB コレクションからデータを検索する方法を学びます。 読み取り操作は、サーバーからドキュメントを検索するコマンドです。
読み取り操作には次の 2 つのタイプがあります。
検索操作: コレクションからドキュメントを検索できます
集計操作: コレクション内のデータを変換
このガイドには、次のセクションが含まれています。
例のサンプル データ では、読み取り操作の例で使用されるサンプル データが提示されます
検索操作では、ドライバーを使用して検索操作を実行する方法について説明します
「集計操作」では、ドライバーを使用して集計操作を実行する方法について説明します
追加情報では、このガイドで言及されている型とメソッドのリソースとAPIドキュメントへのリンクを提供します
サンプルデータの例
このガイドの例では、次のサンプル ドキュメントを使用します。 各ドキュメントは、店舗の在庫内の商品を表し、その分類と単価に関する情報が含まれています。
let docs = vec![ Inventory { item: "candle".to_string(), category: "decor".to_string(), unit_price: 2.89, }, Inventory { item: "blender".to_string(), category: "kitchen".to_string(), unit_price: 38.49, }, Inventory { item: "placemat".to_string(), category: "kitchen".to_string(), unit_price: 3.19, }, Inventory { item: "watering can".to_string(), category: "garden".to_string(), unit_price: 11.99, }, ];
検索操作
検索操作を使用して、MongoDB からデータを取得します。 find()検索操作は、find_one() メソッドと メソッドで構成されています。
一致するドキュメントのすべての検索
条件に一致するすべてのドキュメントを検索するには、 find()メソッドを使用します。 このメソッドは、クエリフィルターをパラメーターとして受け取ります。 クエリフィルターは、一致するドキュメントの基準を形成するフィールドと値で構成されます。
メソッドは、フィルタ条件に一致するドキュメントを検索するために反復処理できるCursorタイプを返します。
このメソッドを使用してデータを検索する例については、 find() の例 を参照してください。
クエリの指定の詳細については、「 クエリの指定 」ガイドを参照してください。
1 つのドキュメントの検索
条件に一致する最初のドキュメントを検索するには、 find_one()メソッドを使用します。 このメソッドは、クエリフィルターをパラメーターとして受け取ります。 クエリフィルターは、一致するドキュメントの基準を形成するフィールドと値で構成されます。
ドキュメントがフィルタ条件に一致する場合、メソッドはSomeの値を持つResult<Option<T>>型を返します。 フィルタ条件に一致するドキュメントがない場合、 find_one()はNoneの値を持つResult<Option<T>>型を返します。
このメソッドを使用してデータを検索する例については、 find_one() の例 を参照してください。
検索動作の変更
FindOptionsオプション ビルダー メソッドをfind()に連鎖させることで、 find()メソッドの動作を変更できます。また、 FindOneOptionsオプション ビルダー メソッドをfind_one()に連鎖させることで、 find_one()メソッドの動作を変更できます。
次の表では、対応するビルダFindOptions FindOneOptionsメソッドを呼び出して設定できる一般的に使用される フィールドと フィールドについて説明しています。
フィールド | 説明 |
|---|---|
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. Type: HintDefault: None |
| The projection to use when returning results. Type: DocumentDefault: None |
| The read concern to use for the find operation. If you don't
set this option, the operation inherits the read concern set for the
collection. To learn more about read concerns, see
Read Concern
in the Server manual. Type: ReadConcern |
| The number of documents to skip when returning results. To learn more
about how to use the skip() builder method, see Skip Returned Results.Type: u64Default: None |
| The sort to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. To learn more about how to use the
sort() builder method, see Sort Results.Type: DocumentDefault: None |
注意
設定オプション
FindOptionsFindOneOptionsオプション ビルダのメソッドを検索操作メソッド呼び出しに直接連結することで、 フィールドと フィールドを設定できます。以前のバージョンのドライバーを使用している場合は、オプション ビルダー メソッドをbuilder()メソッドに連結して、 FindOptionsまたはFindOneOptionsインスタンスを構築する必要があります。 次に、オプション インスタンスをパラメーターとしてfind()またはfind_one()に渡します。
各タイプに指定できる設定の完全なリストについては、 FindOptions と FindOneOptions のAPIドキュメントを参照してください。
例
次のセクションには、 find()メソッドとfindOne()メソッドを使用してフィルター条件に一致するサンプル ドキュメントを取得する例が含まれています。
find() の例
この例では、次のアクションを実行します。
find()メソッドを呼び出しますfind()の値がunit_price12.00未満で、かつ でないドキュメントに一致するクエリフィルターを に渡しますcategory"kitchen"sort()メソッドをfind()に連鎖させ、一致したドキュメントをunit_priceで降順に並べ替えます
let mut cursor = my_coll .find(doc! { "$and": vec! [ doc! { "unit_price": doc! { "$lt": 12.00 } }, doc! { "category": doc! { "$ne": "kitchen" } } ] }) .sort(doc! { "unit_price": -1 }) .await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Inventory { item: "watering can", category: "garden", unit_price: 11.99 } Inventory { item: "candle", category: "decor", unit_price: 2.89 }
find_one() の例
この例では、次のアクションを実行します。
find_one()メソッドを呼び出しますunit_priceの値が20.00以下のドキュメントに一致するクエリフィルターをfind_one()に渡します最初に一致したドキュメントをスキップするには、
skip()メソッドをfind_one()にチェーンします。
let result = my_coll .find_one(doc! { "unit_price": doc! { "$lte": 20.00 } }) .skip(2) .await?; println!("{:#?}", result);
Some( Inventory { item: "watering can", category: "garden", unit_price: 11.99, }, )
集計操作
集計操作 を使用して、コレクションからデータを取得して変換します。 aggregate()メソッドを使用して集計操作を実行できます。
ドキュメント データの集計
aggregate()メソッドは、集計パイプラインをパラメーターとして受け取ります。 集計パイプラインには、データの変換方法を指定する 1 つ以上のステージが含まれます。 ステージには、集計演算子(プレフィックスとして$ )と、その演算子に必要なパラメータが含まれます。
集計の詳細と集計の例については、集計ガイドを参照してください。
このメソッドでは、 Cursorタイプの結果ドキュメントが返されます。 集計パイプラインに$matchステージが含まれていない場合、パイプラインはコレクション内のすべてのドキュメントを処理します。
集計動作を変更する
AggregateOptionsオプション ビルダー メソッドをaggregate()に連鎖させることで、 aggregate()メソッドの動作を変更できます。
次の表では、対応するビルダ メソッドを呼び出して設定できる一般的に使用されるAggregateOptionsフィールドについて説明しています。
フィールド | 説明 |
|---|---|
| Enables writing to temporary files. If true,
aggregation stages can write data to the _tmp subdirectory in the
dbPath directory.Type: boolDefault: false |
| Specifies the maximum number of documents the server returns per
cursor batch. This option sets the number of documents the cursor
keeps in memory rather than the number of documents the cursor
returns. Type: u32Default: 101 documents initially, 16 MB maximum for
subsequent batches |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. Type: HintDefault: None |
| The read concern to use for the find operation. If you don't
set this option, the operation inherits the read concern set for the
collection. To learn more about read concerns, see
Read Concern
in the Server manual. Type: ReadConcern |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
設定の完全なリストについては、AggregateOptions のAPIドキュメントを参照してください。
例
この例では、次のステージを含むパイプラインでaggregate()メソッドを呼び出す方法を示しています。
$groupステージ:categoryフィールドの各値についてunit_priceフィールドの平均を計算$sortステージ: 結果をavg_priceで昇順に並べ替える
let pipeline = vec![ doc! { "$group": doc! { "_id" : doc! {"category": "$category"} , "avg_price" : doc! { "$avg" : "$unit_price" } } }, doc! { "$sort": { "_id.avg_price" : 1 } }, ]; let mut cursor = my_coll.aggregate(pipeline).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Document({"_id": Document({"category": String("decor")}), "avg_price": Double(2.890000104904175)}) Document({"_id": Document({"category": String("kitchen")}), "avg_price": Double(20.840000867843628)}) Document({"_id": Document({"category": String("garden")}), "avg_price": Double(11.989999771118164)})
詳細情報
検索操作の実行可能な例については、次の使用例を参照してください。
このガイドの操作の詳細については、次のドキュメントを参照してください。
集計ガイド
API ドキュメント
このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。