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

聚合(Aggregation)

在本指南中,您可以了解如何使用 MongoDB .NET/C# 驱动程序以执行聚合操作

聚合操作会对 MongoDB 集合中的数据进行处理,并返回计算结果。MongoDB 聚合框架以数据处理管道的概念为模型。文档通过一个或多个阶段组成的管道流转,该管道将文档转化为聚合结果。

聚合操作的功能类似于带有装配线的汽车工厂。 装配线设有配备专用工具的工位来执行特定任务。 例如,在制造汽车时,装配线从制造车架开始。 然后,当车架移动通过装配线时,每个工位都会组装一个单独的零件。 最终产品即成品汽车。

装配线代表聚合管道,各个工位代表聚合阶段,专用工具代表表达式操作符,而成品则代表聚合结果

下表列出了使用查找操作可以执行的不同任务,同时列出了使用聚合操作可以实现的任务作为对比。聚合框架提供了扩展功能,允许您转换和操作数据。

查找操作
聚合操作

选择要返回的特定文档
选择要返回的字段
对结果进行排序
限制结果
对结果进行计数

选择要返回的特定文档
选择要返回的字段
对结果进行排序
对结果进行限制
对结果进行计数
对结果进行分组
重命名字段
计算新字段
汇总数据
连接和合并数据集

执行聚合操作时要考虑以下限制

  • 返回的文档不得违反 BSON 文档大小限制(16 兆字节)。

  • 默认情况下,管道阶段的内存限制为 100 MB。如果需要,可以通过设置传递给 Aggregate() 方法的 AggregateOptions 对象的 AllowDiskUse 属性来超出此限制。

  • $graphLookup阶段的内存严格限制为 100 兆字节,并忽略了 AllowDiskUse 属性。

如需执行聚合,请向 IMongoCollection<TDocument>.Aggregate() 方法传递聚合阶段列表。

注意

此示例使用 Atlas 示例数据集 中的 sample_restaurants.restaurants 集合。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅快速入门。

下面的代码示例可以统计纽约市每个区的面包店数量。为此,它使用包含以下阶段的聚合管道:

  • $match阶段,用于筛选cuisine字段包含值"Bakery"的文档。

  • $group 阶段按 borough 字段对匹配的文档进行分组,从而为该字段的每个不同值累积文档数。

下文将通过使用 LINQ、构建器和 BsonDocument 方法来创建和组合示例管道中使用的聚合阶段,从而实现本示例。

// Defines a queryable collection object as a prerequisite to using LINQ
var queryableCollection = collection.AsQueryable();
// Defines the query with $match and $group stages
var query = queryableCollection
.Where(r => r.Cuisine == "Bakery")
.GroupBy(r => r.Borough)
.Select(g => new { _id = g.Key, Count = g.Count() });
// Executes the query and prints the aggregated results
foreach (var result in query.ToList())
{
Console.WriteLine(result);
}
{ _id = Bronx, Count = 71 }
{ _id = Brooklyn, Count = 173 }
{ _id = Staten Island, Count = 20 }
{ _id = Missing, Count = 2 }
{ _id = Manhattan, Count = 221 }
{ _id = Queens, Count = 204 }

要学习;了解有关使用 LINQ 构建聚合管道的更多信息,请参阅 LINQ 事务语法 for Aggregation Operations 指南。

// Defines the $match aggregation stage
var matchFilter = Builders<Restaurant>.Filter.Eq(r => r.Cuisine, "Bakery");
// Defines the aggregation pipeline with the $match and $group aggregation stages
var pipeline = new EmptyPipelineDefinition<Restaurant>()
.Match(matchFilter)
.Group(r => r.Borough,
g => new
{
_id = g.Key,
Count = g.Count()
}
);
// Executes the aggregation pipeline
var results = collection.Aggregate(pipeline).ToList();
// Prints the aggregated results
foreach (var result in results)
{
Console.WriteLine(result);
}
{ _id = Bronx, Count = 71 }
{ _id = Brooklyn, Count = 173 }
{ _id = Staten Island, Count = 20 }
{ _id = Missing, Count = 2 }
{ _id = Manhattan, Count = 221 }
{ _id = Queens, Count = 204 }

要了解使用构建器构建聚合管道的更多信息,请参阅《使用构建器进行操作》指南中的构建聚合管道部分。

// Defines the $match and $group aggregation stages
var matchStage = new BsonDocument
{
{
"$match",
new BsonDocument
{
{ "cuisine", "Bakery" }
}
}
};
var groupStage = new BsonDocument
{
{
"$group",
new BsonDocument
{
{ "_id", "$borough" },
{ "count", new BsonDocument("$sum", 1) }
}
}
};
// Executes the aggregation pipeline
var pipeline = new[] { matchStage, groupStage };
var results = collection.Aggregate<BsonDocument>(pipeline).ToList();
// Prints the aggregated results
foreach (BsonDocument result in results)
{
Console.WriteLine(result);
}
{ "_id" : "Brooklyn", "count" : 173 }
{ "_id" : "Manhattan", "count" : 221 }
{ "_id" : "Bronx", "count" : 71 }
{ "_id" : "Missing", "count" : 2 }
{ "_id" : "Staten Island", "count" : 20 }
{ "_id" : "Queens", "count" : 204 }

有关聚合阶段的完整列表,请参阅 聚合阶段,详见 MongoDB Server 手册。

要了解有关组装聚合管道的更多信息并查看示例,请参阅聚合管道。

要了解有关创建管道阶段的更多信息,请参阅聚合阶段。

要了解如何解释 MongoDB 聚合操作,请参阅解释结果查询计划。

有关本指南中讨论的聚合操作的更多信息,请参阅以下 API 文档: