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 ドライバー
/ /

個別のフィールド値の取得

このガイドでは、 .NET/ C#ドライバーを使用して、コレクション全体で指定されたフィールドの個別の値を検索する方法を学習できます。

コレクション内では、異なるドキュメントによって単一のフィールドの異なる値が含まれる場合があります。 例、restaurantsコレクション内の 1 つのドキュメントの borough 値は "Manhattan" で、別のドキュメントの borough 値は "Queens" です。 .NET/ C#ドライバーを使用すると、コレクション内の複数のドキュメントにわたってフィールドに含まれるすべての一意の値を検索できます。

このガイドの例では、 Atlasサンプルデータセットsample_restaurants.restaurantsコレクションを使用します。MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、.NET/C#ドライバーを使い始めるを参照してください。

このページの例では、次の Restaurantクラスを使用して、コレクション内のドキュメントをモデル化します。

public class Restaurant {
public ObjectId? Id { get; set; }
[BsonElement("name")]
public string? Name { get; set; }
[BsonElement("cuisine")]
public string? Cuisine { get; set; }
[BsonElement("borough")]
public string? Borough { get; set; }
}

指定されたフィールドの個別の値を検索するには、IMongoCollection<TDocument>インスタンスの Distinct() メソッドまたは DistinctAsync() メソッドを呼び出し、個別の値を検索するフィールドの名前を渡します。

次の例では、 restaurantsコレクション内の boroughフィールドの個別の値を取得します。 対応するコードを表示するには、Synchronous タブまたは Asynchronousタブを選択します。

var results = collection.Distinct<string>(r => r.Borough, Builders<Restaurant>.Filters.Empty).ToList();
foreach (var result in results)
{
Console.WriteLine(result);
}
Bronx
Brooklyn
Manhattan
Missing
Queens
Staten Island
var results = await collection.DistinctAsync<string>(r => r.Borough, Builders<Restaurant>.Filters.Empty);
await results.ForEachAsync(result => Console.WriteLine(result));
Bronx
Brooklyn
Manhattan
Missing
Queens
Staten Island

この操作では、個別の boroughフィールド値ごとにアクセスするために反復処理できるカーソルが返されます。 boroughフィールドでは複数のドキュメントが同じ値になっていますが、各値は結果に 1 回だけ表示されます。

Distinct() メソッドと DistinctAsync() メソッドにクエリフィルターを提供すると、コレクション内のドキュメントのサブセット内で個別のフィールド値を検索できます。クエリフィルターは、操作内のドキュメントを一致させるために使用される検索条件を指定する式です。クエリフィルターの作成の詳細については、クエリフィルターの作成ガイドを参照してください。

次の例では、 cuisineフィールドの値が "Italian" であるすべてのドキュメントの boroughフィールドの個別の値を取得します。 対応するコードを表示するには、Synchronous タブまたは Asynchronousタブを選択します。

var filter = Builders<Restaurant>.Filter.Eq(r => r.Cuisine, "Italian");
var results = collection.Distinct<string>(r => r.Borough, filter).ToList();
foreach (var result in results)
{
Console.WriteLine(result);
}
Bronx
Brooklyn
Manhattan
Queens
Staten Island
var filter = Builders<Restaurant>.Filter.Eq(r => r.Cuisine, "Italian");
var results = await collection.DistinctAsync<string>(r => r.Borough, filter);
await results.ForEachAsync(result => Console.WriteLine(result));
Bronx
Brooklyn
Manhattan
Queens
Staten Island

任意のパラメータとして DistinctOptionsインスタンスを指定することで、Distinct() メソッドと DistinctAsync() メソッドの動作を変更できます。 次の表では、DistinctOptionsインスタンスに設定できるプロパティについて説明します。

方式
説明

Collation

Sets the collation to use for the operation. See the Collation section of this page for more information.
Default: null
Data type: Collation

MaxTime

Sets the maximum amount of time that the operation can run.
Data type: TimeSpan

Comment

Attaches a comment to the operation.
Data type: BsonValue or string

次の例では、 boroughフィールド値が "Bronx" で、かつ cuisineフィールド値が "Pizza" であるすべてのドキュメントの nameフィールドの個別の値を取得します。 次に、Distinct() メソッドに DistinctOptionsインスタンスを提供して操作にコメントを追加します。

SynchronousAsynchronous対応するコードを表示するには、 タブまたは タブを選択します。

var cuisineFilter = Builders<Restaurant>.Filter.Eq(r => r.Cuisine, "Pizza");
var boroughFilter = Builders<Restaurant>.Filter.Eq(r => r.Borough, "Bronx");
var filter = Builders<Restaurant>.Filter.And(cuisineFilter, boroughFilter);
var options = new DistinctOptions {
Comment = "Find all Italian restaurants in the Bronx"
};
var results = collection.Distinct<string>(r => r.Name, filter).ToList();
foreach (var result in results)
{
Console.WriteLine(result);
}
$1.25 Pizza
18 East Gunhill Pizza
2 Bros
Aenos Pizza
Alitalia Pizza Restaurant
Amici Pizza And Pasta
Angie'S Cafe Pizza
...
var cuisineFilter = Builders<Restaurant>.Filter.Eq(r => r.Cuisine, "Pizza");
var boroughFilter = Builders<Restaurant>.Filter.Eq(r => r.Borough, "Bronx");
var filter = Builders<Restaurant>.Filter.And(cuisineFilter, boroughFilter);
var options = new DistinctOptions {
Comment = "Find all Italian restaurants in the Bronx"
};
var results = await collection.DistinctAsync<string>(r => r.Name, filter, options);
await results.ForEachAsync(result => Console.WriteLine(result));
$1.25 Pizza
18 East Gunhill Pizza
2 Bros
Aenos Pizza
Alitalia Pizza Restaurant
Amici Pizza And Pasta
Angie'S Cafe Pizza
...

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

次の表では、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マニュアルの 照合 ページを参照してください。

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

戻る

ドキュメントをカウント

項目一覧