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()の動作を変更できます。また、 FindOneOptionsインスタンスを渡すことでfind_one()の動作を変更できます。
各設定でデフォルト値を使用するには、オプション パラメータとして値Noneを指定します。
次の表では、 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 |
注意
インスタンス化オプション
Rust ドライバーは、 FindOneOptionsやFindOptionsなどの多数のさまざまなタイプを作成するためのビルダ設計パターンを実装します。 各タイプのbuilder()メソッドを使用して、オプション ビルダー関数を 1 つずつ連鎖させてオプション インスタンスを構築できます。
各タイプに指定できる設定の完全なリストについては、 FindOptions と FindOneOptions のAPIドキュメントを参照してください。
例
次のセクションには、 find()メソッドとfindOne()メソッドを使用してフィルター条件に一致するサンプル ドキュメントを取得する例が含まれています。
find() の例
以下の例では、次のパラメータを使用してfind()メソッドを呼び出す方法を示しています。
unit_priceの値が12.00未満で、かつcategoryの値が"kitchen"でないドキュメントに一致するクエリフィルター一致したドキュメントを
unit_priceで降順に並べ替えるFindOptionsインスタンス
let opts = FindOptions::builder() .sort(doc! { "unit_price": -1 }) .build(); let mut cursor = my_coll.find( doc! { "$and": vec! [ doc! { "unit_price": doc! { "$lt": 12.00 } }, doc! { "category": doc! { "$ne": "kitchen" } } ] }, opts ).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_price20.00最初に一致したドキュメントをスキップする
FindOneOptionsインスタンス
let opts = FindOneOptions::builder().skip(2).build(); let result = my_coll.find_one( doc! { "unit_price": doc! { "$lte": 20.00 } }, opts ).await?; println!("{:#?}", result);
Some( Inventory { item: "watering can", category: "garden", unit_price: 11.99, }, )
集計操作
集計操作 を使用して、コレクションからデータを取得して変換します。 aggregate()メソッドを使用して集計操作を実行できます。
ドキュメント データの集計
aggregate()メソッドは、集計パイプラインをパラメーターとして受け取ります。 集計パイプラインには、データの変換方法を指定する 1 つ以上のステージが含まれます。 ステージには、集計演算子(プレフィックスとして$ )と、その演算子に必要なパラメータが含まれます。
集計の詳細と集計の例については、集計ガイドを参照してください。
このメソッドでは、 Cursorタイプの結果ドキュメントが返されます。 集計パイプラインに$matchステージが含まれていない場合、パイプラインはコレクション内のすべてのドキュメントを処理します。
集計動作を変更する
任意のパラメータとしてAggregateOptionsインスタンスを渡すことで、 aggregate()の動作を変更できます。
各設定でデフォルト値を使用するには、オプション パラメータとして値Noneを指定します。
次の表では、 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()メソッドを呼び出す方法を示しています。
ドキュメントを
categoryフィールドでグループ化し、categoryによりunit_priceフィールドの平均を計算する$groupステージ$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, None).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ドキュメントを参照してください。