Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

ドキュメントの検索

このガイドでは、読み取り操作を使用して 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() の例 を参照してください。

クエリの指定の詳細については、「 クエリの指定 」ガイドを参照してください。

条件に一致する最初のドキュメントを検索するには、 find_one()メソッドを使用します。 このメソッドは、クエリフィルターをパラメーターとして受け取ります。 クエリフィルターは、一致するドキュメントの基準を形成するフィールドと値で構成されます。

ドキュメントがフィルタ条件に一致する場合、メソッドはSomeの値を持つResult<Option<T>>型を返します。 フィルタ条件に一致するドキュメントがない場合、 find_one()Noneの値を持つResult<Option<T>>型を返します。

このメソッドを使用してデータを検索する例については、 find_one() の例 を参照してください。

FindOptionsオプション ビルダー メソッドをfind()に連鎖させることで、 find()メソッドの動作を変更できます。また、 FindOneOptionsオプション ビルダー メソッドをfind_one()に連鎖させることで、 find_one()メソッドの動作を変更できます。

次の表では、対応するビルダFindOptions FindOneOptionsメソッドを呼び出して設定できる一般的に使用される フィールドと フィールドについて説明しています。

フィールド
説明

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

The index to use for the operation. To learn more about indexes, see Indexes in the Server manual.

Type: Hint
Default: None

projection

The projection to use when returning results. To learn more about projections, see the Specify Fields to Return guide.

Type: Document
Default: None

read_concern

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

skip

The number of documents to skip when returning results. To learn more about how to use the skip() builder method, see Skip.

Type: u64
Default: None

sort

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.

Type: Document
Default: None

注意

設定オプション

FindOptionsFindOneOptionsオプション ビルダのメソッドを検索操作メソッド呼び出しに直接連結することで、 フィールドと フィールドを設定できます。以前のバージョンのドライバーを使用している場合は、オプション ビルダー メソッドをbuilder()メソッドに連結して、 FindOptionsまたはFindOneOptionsインスタンスを構築する必要があります。 次に、オプション インスタンスをパラメーターとしてfind()またはfind_one()に渡します。

各タイプに指定できる設定の完全なリストについては、 FindOptions FindOneOptions のAPIドキュメントを参照してください。

次のセクションには、 find()メソッドとfind_one()メソッドを使用してフィルター条件に一致するサンプル ドキュメントを取得する例が含まれています。

この例では、次のアクションを実行します。

  • find()メソッドを呼び出します

  • find()の値がunit_price 12.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 }

この例では、 sample_restaurantsデータベース内のrestaurantsコレクションからクエリフィルターに一致するドキュメントを検索します。 find() メソッドは、cuisineフィールドの値が "French" であるすべてのドキュメントを返します。

取得された各ドキュメントは、 Document タイプまたはカスタムデータ型としてモデル化できます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T> 型パラメータを次のいずれかの値に置き換えます。

  • <Document>:コレクションドキュメントをBSONドキュメントとして検索して出力します

  • <Restaurant>: コードの上部で定義された Restaurant 構造体のインスタンスとしてコレクションドキュメントを検索して出力します

AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。

use mongodb::{
bson::doc,
Client,
Collection
};
use futures::TryStreamExt;
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let mut cursor = my_coll.find(
doc! { "cuisine": "French" }
).await?;
while let Some(doc) = cursor.try_next().await? {
println!("{:#?}", doc);
}
Ok(())
}
use mongodb::{
bson::doc,
sync::{Client, Collection}
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let mut cursor = my_coll.find(
doc! { "cuisine": "French" }
).run()?;
for result in cursor {
println!("{:#?}", result?);
}
Ok(())
}

コレクションの型パラメータに基づいて対応するコード出力を表示するには、[BSON Document Results タブまたは Restaurant Struct Resultsタブを選択します。

...
Some(
Document({
"_id": ObjectId(
"...",
),
...
"name": String(
"Cafe Un Deux Trois",
),
...
}),
),
Some(
Document({
"_id": ObjectId(
"...",
),
...
"name": String(
"Calliope",
),
...
}),
)
...
...
Restaurant {
name: "Cafe Un Deux Trois",
cuisine: "French",
}
Restaurant {
name: "Calliope",
cuisine: "French",
}
...

この例では、次のアクションを実行します。

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

この例では、 sample_restaurantsデータベース内の restaurantsコレクションからクエリフィルターに一致するドキュメントを検索します。 find_one() メソッドは、nameフィールドの値が "Tompkins Square Bagels" である最初のドキュメントを返します。

取得されたドキュメントは、 Document 型またはカスタムデータ型としてモデル化できます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T> 型パラメータを次のいずれかの値に置き換えます。

  • <Document>:コレクションドキュメントをBSONドキュメントとして検索して出力します

  • <Restaurant>: コードの上部で定義された Restaurant 構造体のインスタンスとしてコレクションドキュメントを検索して出力します

各実行時に対応するコードを表示するには、 AsynchronousタブまたはSynchronousタブを選択します。

use mongodb::{
bson::doc,
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let result = my_coll.find_one(
doc! { "name": "Tompkins Square Bagels" }
).await?;
println!("{:#?}", result);
Ok(())
}
use mongodb::{
bson::doc,
sync::{Client, Collection}
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let result = my_coll.find_one(
doc! { "name": "Tompkins Square Bagels" }
).run()?;
println!("{:#?}", result);
Ok(())
}

コレクションの型パラメータに基づいて対応するコード出力を表示するには、[BSON Document Result タブまたは Restaurant Struct Resultタブを選択します。

Some(
Document({
"_id": ObjectId(
"...",
),
...
"name": String(
"Tompkins Square Bagels",
),
...
}),
)
Some(
Restaurant {
name: "Tompkins Square Bagels",
cuisine: "American",
},
)

集計操作 を使用して、コレクションからデータを取得して変換します。 aggregate()メソッドを使用して集計操作を実行できます。

aggregate()メソッドは、集計パイプラインをパラメーターとして受け取ります。 集計パイプラインには、データの変換方法を指定する 1 つ以上のステージが含まれます。 ステージには、集計演算子(プレフィックスとして$ )と、その演算子に必要なパラメータが含まれます。

集計の詳細と集計の例については、集計ガイドを参照してください。

このメソッドでは、 Cursorタイプの結果ドキュメントが返されます。 集計パイプラインに$matchステージが含まれていない場合、パイプラインはコレクション内のすべてのドキュメントを処理します。

AggregateOptionsオプション ビルダー メソッドをaggregate()に連鎖させることで、 aggregate()メソッドの動作を変更できます。

次の表では、対応するビルダ メソッドを呼び出して設定できる一般的に使用されるAggregateOptionsフィールドについて説明しています。

フィールド
説明

allow_disk_use

Enables writing to temporary files. If true, aggregation stages can write data to the _tmp subdirectory in the dbPath directory.

Type: bool
Default: false

batch_size

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: u32
Default: 101 documents initially, 16 MB maximum for subsequent batches

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

The index to use for the operation. To learn more about indexes, see Indexes in the Server manual.

Type: Hint
Default: None

read_concern

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

write_concern

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ドキュメントを参照してください。

戻る

クエリを指定する