Overview
このガイドでは、MongoDB .NET/C# ドライバーを使用して、読み取り操作により MongoDB コレクションからデータを検索する方法を学習できます。Find()
メソッドを呼び出して、基準のセットに一致するドキュメントを検索できます。
Tip
インタラクティブ ラボ
このページには、 Find()
メソッドを使用してデータを取得する方法を示す短いインタラクティブ ラボが含まれています。 MongoDB やコード エディターをインストールしなくても、ブラウザ ウィンドウでこのラボを直接完了できます。
ラボを開始するには、ページ上部の [ Open Interactive Tutorialボタンをクリックします。 ラボを全画面形式に展開するには、ラボ ペインの右上隅にある全画面ボタン( ⛶ )をクリックします。
サンプル データ
このガイドの例では、 Atlasサンプルデータセット の sample_restaurants.restaurants
コレクションを使用します。MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、.NET/C#ドライバーを使い始めるを参照してください。
このページの例では、次の Restaurant
クラス、Address
クラス、GradeEntry
クラスをモデルとして使用します。
public class Restaurant { public ObjectId Id { get; set; } public string Name { get; set; } [ ] public string RestaurantId { get; set; } public string Cuisine { get; set; } public Address Address { get; set; } public string Borough { get; set; } public List<GradeEntry> Grades { get; set; } }
public class Address { public string Building { get; set; } [ ] public double[] Coordinates { get; set; } public string Street { get; set; } [ ] public string ZipCode { get; set; } }
public class GradeEntry { public DateTime Date { get; set; } public string Grade { get; set; } public float? Score { get; set; } }
注意
restaurants
コレクションのドキュメントは、スニペット ケースの命名規則を使用します。このガイドの例では、ConventionPack
を使用してコレクション内のフィールドをパスカル ケースに逆シリアル化し、Restaurant
クラスのプロパティにマップします。
カスタム直列化について詳しくは、「カスタム直列化」を参照してください。
ドキュメントの検索
コレクションからドキュメントを検索するには、Find()
メソッドを使用します。Find()
メソッドはクエリフィルターを受け取り、一致するすべてのドキュメントを返します。クエリフィルターは、クエリで検索するドキュメントを指定するオブジェクトです。
クエリフィルターの詳細については、クエリフィルターの作成を参照してください。
1 つのドキュメントの検索
コレクション内の 1 つのドキュメントを検索するには、検索するドキュメントの基準を指定するクエリフィルターを渡し、FirstOrDefault()
メソッドまたは FirstOrDefaultAsync()
メソッドを連鎖させます。複数のドキュメントがクエリフィルターに一致する場合、これらのメソッドは検索した結果から最初に一致するドキュメントを返します。クエリフィルターに一致するドキュメントがない場合、メソッドは null
を返します。
var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();
var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();
Find()
メソッドを使用して 1 つのドキュメントを検索する完全な例については、「追加情報 」を参照してください。
複数ドキュメントの検索
コレクション内の複数のドキュメントを検索するには、検索するドキュメントの基準を指定するクエリフィルターを Find()
メソッドに渡します。
カーソルを使用して、Find()
メソッドによって返されたドキュメントを反復処理できます。カーソルは、アプリケーションがデータベースの結果を反復処理しながら、特定の時点でメモリ内に結果のサブセットのみを保持できるようにするメカニズムです。カーソルは、Find()
メソッドが大量のドキュメントを返す場合に便利です。
カーソルを使用してドキュメントを反復処理するには、検索するドキュメントの基準を指定するクエリフィルターを Find()
メソッドに渡し、ToCursor()
メソッドまたは ToCursorAsync()
メソッドをチェーンします。同期または非同期の例を表示するには、対応するタブを選択します。
var restaurants = _restaurantsCollection.Find(filter).ToCursor();
var restaurants = await _restaurantsCollection.Find(filter).ToCursorAsync();
返されるドキュメントの数が少ない場合、または結果を List
オブジェクトとして返す必要がある場合は、ToList()
メソッドまたは ToListAsync()
メソッドを使用します。
コレクション内の複数のドキュメントを検索し、それらをリストとしてメモリに保持するには、検索するドキュメントの基準を指定するクエリフィルターを Find()
メソッドに渡し、ToList()
メソッドまたは ToListAsync()
メソッドをチェーンします。同期または非同期の例を表示するには、対応するタブを選択します。
var restaurants = _restaurantsCollection.Find(filter).ToList();
var restaurants = await _restaurantsCollection.Find(filter).ToListAsync();
Find()
メソッドを使用して複数のドキュメントを検索する完全な例については、「追加情報 」を参照してください。
注意
すべてのドキュメントの検索
コレクション内のすべてのドキュメントを検索するには、Find()
メソッドに空のフィルターを渡します。
var filter = Builders<Restaurant>.Filter.Empty; var allRestaurants = _restaurantsCollection.Find(filter);
Find()
メソッドを使用してすべてのドキュメントを検索する完全に実行可能な例については、「追加情報 」を参照してください。
検索動作の変更
FindOptions
オブジェクトを渡すことで、Find()
メソッドの動作を変更できます。
一般的に使用されるオプションは、次の方法で構成できます。
方式 | 説明 |
---|---|
| Gets or sets the maximum number of documents within each
batch returned in a query result. If batchSize is not set, the Find()
method has an initial batch size of 101 documents and a maximum size of 16
mebibytes (MiB) for each subsequent batch. This option can enforce a smaller
limit than 16 MiB, but not a larger one. If you set batchSize to a limit that
results in batches larger than 16 MiB, this option has no effect and the
Find() method uses the default batch size. |
| Sets the collation options. See the
Collation section of this page for more information. |
| Sets the comment to the query. To learn more about query comments,
see the $comment page. |
| Sets the hint for which index to use. |
| Sets the maximum execution time on the server for this operation. |
照合
操作の 照合 を構成するには、 照合クラスのインスタンスを作成します。
次の表では、Collation
コンストラクターが受け入れるパラメーターを説明しています。また、各設定の値を読み取るために使用できる対応するクラスプロパティも一覧表示されます。
Parameter | 説明 | クラスプロパティ |
---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of
supported locales,
see Collation Locales and Default Parameters
in the MongoDB Server Manual. If you want to use simple binary comparison, use the Collation.Simple static
property to return a Collation object with the locale set to "simple" .Data Type: string |
|
| (Optional) Specifies whether to include case comparison. When this argument is true , the driver's behavior depends on the value of
the strength argument:- If strength is CollationStrength.Primary , the driver compares base
characters and case.- If strength is CollationStrength.Secondary , the driver compares base
characters, diacritics, other secondary differences, and case.- If strength is any other value, this argument is ignored.When this argument is false , the driver doesn't include case comparison at
strength level Primary or Secondary .Data Type: boolean Default: false |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. Data Type: CollationCaseFirst Default: CollationCaseFirst.Off |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: CollationStrength Default: CollationStrength.Tertiary |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. If this argument is true , the driver compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the driver treats the values
as 10 and 2, and finds 10 to be greater.If this argument is false or excluded, the driver compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the driver
compares one character at a time. Because "1" is less than "2", the driver finds
"10" to be less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: boolean Default: false |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. Data Type: CollationAlternate Default: CollationAlternate.NonIgnorable (spaces and punctuation are
considered base characters) |
|
| (Optional) Specifies which characters the driver considers ignorable when
the alternate argument is CollationAlternate.Shifted .Data Type: CollationMaxVariable Default: CollationMaxVariable.Punctuation (the driver ignores punctuation
and spaces) |
|
| (Optional) Specifies whether the driver normalizes text as needed. Most text doesn't require normalization. For more information about
normalization, see the ICU documentation. Data Type: boolean Default: false |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: boolean Default: false |
|
照合の詳細については、 MongoDB Serverマニュアルの 照合 ページを参照してください。
例
この例では、次のアクションを実行します。
cuisine
フィールドに "Pizza" が含まれるすべてのドキュメントを検索BatchSize
を3
に設定結果をカーソルに保存
カーソルが参照するドキュメントを印刷
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza"); var findOptions = new FindOptions { BatchSize = 3 }; using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor()) { foreach (var r in cursor.ToEnumerable()) { WriteLine(r.Name); } }
Pizza Town Victoria Pizza ...
詳細情報
クエリフィルターの詳細については、クエリフィルターの作成を参照してください。
LINQ を使用してクエリを指定する方法については、「 集計操作用の LINQシンタックス 」を参照してください。
検索操作の実行可能な例については、次の使用例を参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。