Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
C#/.NET ドライバー
/ /

Retrieve Data

このガイドでは、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; }
[BsonElement("restaurant_id")]
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; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
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 つのドキュメントを検索するには、検索するドキュメントの基準を指定するクエリフィルターを渡し、FirstOrDefault() メソッドまたは FirstOrDefaultAsync() メソッドを連鎖させます。複数のドキュメントがクエリフィルターに一致する場合、これらのメソッドは検索した結果から最初に一致するドキュメントを返します。クエリフィルターに一致するドキュメントがない場合、メソッドは null を返します。

var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();
var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();

Tip

最初のドキュメント

ソート条件が指定されていない場合、 FirstOrDefault()メソッドはディスク上の自然な順序で最初のドキュメントを返します。

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() メソッドの動作を変更できます。

一般的に使用されるオプションは、次の方法で構成できます。

方式
説明

BatchSize

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.

Collation

Sets the collation options. See the Collation section of this page for more information.

Comment

Sets the comment to the query. To learn more about query comments, see the $comment page.

Hint

Sets the hint for which index to use.

MaxTime

Sets the maximum execution time on the server for this operation.

利用可能なオプションの完全なリストを確認するには、「 FindOptions プロパティ 」を参照してください。

操作の 照合 を構成するには、 照合クラスのインスタンスを作成します。

次の表では、Collation コンストラクターが受け入れるパラメーターを説明しています。また、各設定の値を読み取るために使用できる対応するクラスプロパティも一覧表示されます。

Parameter
説明
クラスプロパティ

locale

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

Locale

caseLevel

(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

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Default: CollationStrength.Tertiary

Strength

numericOrdering

(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

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(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

Normalization

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: boolean
Default: false

Backwards

照合の詳細については、 MongoDB Serverマニュアルの 照合 ページを参照してください。

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

  • cuisine フィールドに "Pizza" が含まれるすべてのドキュメントを検索

  • BatchSize3 に設定

  • 結果をカーソルに保存

  • カーソルが参照するドキュメントを印刷

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
...

Tip

クリーンアップ

カーソルが使用されなくなったら Dispose() メソッドを自動的に呼び出すには、 using ステートメント を使用してカーソルを作成します。

クエリフィルターの詳細については、クエリフィルターの作成を参照してください。

LINQ を使用してクエリを指定する方法については、「 集計操作用の LINQシンタックス 」を参照してください。

検索操作の実行可能な例については、次の使用例を参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。

戻る

クエリを指定する

項目一覧