对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

检索不同字段值

在本指南中,您可以学习;了解如何使用.NET/ C#驱动程序检索集合中指定字段的不同值。

在集合中,不同文档的单个字段可能包含不同值。 示例,restaurants集合中一个文档的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字段的非重复值。 选择 SynchronousAsynchronous标签页以查看相应的代码。

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

该操作会返回一个游标,您可以遍历该游标以访问权限每个不同的 borough字段值。 尽管多个文档在 borough字段中具有相同的值,但每个值仅在结果中出现一次。

您可以为 Distinct()DistinctAsync() 方法提供查询过滤,以在集合的文档子集中查找不同的字段值。查询过滤是一个表达式,用于指定在操作中匹配文档的搜索条件。有关创建查询过滤的更多信息,请参阅“创建查询筛选器”指南。

以下示例检索 cuisine字段值为 "Italian" 的所有文档的 borough字段的非重复值。 选择 SynchronousAsynchronous标签页以查看相应的代码。

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);
}
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));

您可以通过提供 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

设置操作可以运行的最长时间。
数据类型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);
}
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));

要为操作配置排序规则,请创建 Collation 类的实例。

下表描述了 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

(可选)指定是否包含大小写比较。

当此参数为 true 时,驱动程序的行为取决于 strength 参数的值:

- 如果 strengthCollationStrength.Primary,则驱动程序会比较基本字符和大小写。
- 如果 strengthCollationStrength.Secondary,则驱动程序会比较基本字符、变音符、其他次要差异和大小写。
- 如果 strength 为任何其他值,则会忽略此参数。

当此参数为 false 时,驱动程序不会在强度级别 PrimarySecondary 包含大小写比较。

数据类型boolean
默认值false

CaseLevel

caseFirst

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

Data Type: CollationCaseFirst
Default: CollationCaseFirst.Off

CaseFirst

strength

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

Data Type: CollationStrength
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.

Data Type: CollationAlternate
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.

Data Type: CollationMaxVariable
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

(可选)指定包含变音符号的字符串是否从字符串的后部到前部排序。

数据类型boolean
默认false

Backwards

有关排序规则的更多信息,请参阅MongoDB Server手册中的排序规则页面。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: