Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

$sortByCount(聚合阶段)

$sortByCount

根据指定表达式的值对传入文档进行分组,然后计算每个不同群组中的文档数量。

每个输出文档都包含两个字段:一个包含不同组值的 _id 字段,以及一个包含属于该分组或类别的文档数量的 count 字段。

文档按 count 降序排序。

$sortByCount 阶段具有以下原型形式:

{ $sortByCount: <expression> }
字段
说明

expression

作为分组依据的表达式。您可以指定除文档字面值以外的任何表达式。

如需指定字段路径,请在字段名称前加上美元符号 $,并用引号括起来。例如,要按字段 employee 进行分组,请将 "$employee" 指定为表达式。

{ $sortByCount: "$employee" }

虽然不能为群组依据表达式指定文档字面量,但可以指定计算结果为文档的字段或表达式。 示例,如果employeebusiness 字段是文档字段,那么以下计算结果为文档的$mergeObjects 表达式就是$sortByCount 的有效参数:

{ $sortByCount: { $mergeObjects: [ "$employee", "$business" ] } }

但是,以下带有文档字面表达式的示例无效:

{ $sortByCount: { lname: "$employee.last", fname: "$employee.first" } }

提示

从 MongoDB 6.0 开始,需要 100 兆字节以上内存容量的管道阶段默认将临时文件写入磁盘。这些临时文件在管道执行期间持续存在,并且可能影响实例上的存储空间。在 MongoDB 的早期版本中,您必须将 { allowDiskUse: true } 传递给单个 findaggregate 命令才能启用此行为。

单个 findaggregate 命令可以通过以下任一方式覆盖 allowDiskUseByDefault 参数:

  • 使用 { allowDiskUse: true } 以允许在 allowDiskUseByDefault 设置为 false 时将临时文件写入磁盘

  • 使用 { allowDiskUse: false } 以禁止在 allowDiskUseByDefault 设置为 true 时将临时文件写入磁盘

注意

对于MongoDB Atlas,建议配置存储自动伸缩,以防止长时间运行的查询用临时文件填满存储。

如果您的Atlas 集群使用存储自动伸缩,则临时文件可能会导致集群扩展到下一个存储层级。

有关更多详细信息,请参阅聚合管道限制。

$sortByCount 阶段相当于以下的 $group + $sort 序列:

{ $group: { _id: <expression>, count: { $sum: 1 } } },
{ $sort: { count: -1 } }

请考虑包含以下文档的集合 exhibits

db.exhibits.insertMany(
[
{ _id: 1, title: "The Pillars of Society", artist: "Grosz", year: 1926, tags: [ "painting", "satire", "Expressionism", "caricature" ] },
{ _id: 2, title: "Melancholy III", artist: "Munch", year: 1902, tags: [ "woodcut", "Expressionism" ] },
{ _id: 3, title: "Dancer", artist: "Miro", year: 1925, tags: [ "oil", "Surrealism", "painting" ] },
{ _id: 4, title: "The Great Wave off Kanagawa", artist: "Hokusai", tags: [ "woodblock", "ukiyo-e" ] },
{ _id: 5, title: "The Persistence of Memory", artist: "Dali", year: 1931, tags: [ "Surrealism", "painting", "oil" ] },
{ _id: 6, title: "Composition VII", artist: "Kandinsky", year: 1913, tags: [ "oil", "painting", "abstract" ] },
{ _id: 7, title: "The Scream", artist: "Munch", year: 1893, tags: [ "Expressionism", "painting", "oil" ] },
{ _id: 8, title: "Blue Flower", artist: "O'Keefe", year: 1918, tags: [ "abstract", "painting" ] }
]
)

以下操作会unwinds tags 数组并使用$sortByCount阶段来计算每个标签相关的文档数量:

db.exhibits.aggregate( [ { $unwind: "$tags" }, { $sortByCount: "$tags" } ] )

操作将返回以下文档,按计数降序排序:

[
{ _id: "painting", count: 6 },
{ _id: "oil", count: 4 },
{ _id: "Expressionism", count: 3 },
{ _id: "Surrealism", count: 2 },
{ _id: "abstract", count: 2 },
{ _id: "woodblock", count: 1 },
{ _id: "woodcut", count: 1 },
{ _id: "ukiyo-e", count: 1 },
{ _id: "satire", count: 1 },
{ _id: "caricature", count: 1 }
]

本页上的C#示例使用Atlas示例数据集中的 sample_mflix数据库。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅MongoDB .NET/ C#驱动程序文档中的入门

以下 Movie 类对 sample_mflix.movies 集合中的文档进行建模:

[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("title")]
public string Title { get; set; } = null!;
[BsonElement("year")]
public int? Year { get; set; }
[BsonElement("runtime")]
public int? Runtime { get; set; }
[BsonElement("rated")]
public string? Rated { get; set; }
[BsonElement("metacritic")]
public int Metacritic { get; set; }
[BsonElement("plot")]
public string? Plot { get; set; }
[BsonElement("type")]
public string? Type { get; set; }
[BsonElement("cast")]
public string[]? Cast { get; set; }
[BsonElement("directors")]
public string[]? Directors { get; set; }
[BsonElement("writers")]
public string[]? Writers { get; set; }
[BsonElement("imdb")]
public ImdbData? Imdb { get; set; }
}

要使用MongoDB .NET/C#驱动程序将 $sortByCount 阶段添加到聚合管道,请对 PipelineDefinition对象调用 SortByCount() 方法。

以下示例创建了一个管道阶段,该阶段根据传入的 Movie 文档的 Rated字段的值对其进行分组,然后返回群组中的文档数:

var pipeline = new EmptyPipelineDefinition<Movie>()
.SortByCount(m => m.Rated);
{ "_id" : "...", "count" : 9894 }
{ "_id" : "R", "count" : 5537 }
{ "_id" : "PG-13", "count" : 2321 }
{ "_id" : "PG", "count" : 1852 }
{ "_id" : "APPROVED", "count" : 709 }
{ "_id" : "G", "count" : 477 }
{ "_id" : "PASSED", "count" : 181 }
{ "_id" : "TV-14", "count" : 89 }
{ "_id" : "TV-PG", "count" : 76 }
{ "_id" : "TV-MA", "count" : 60 }
{ "_id" : "TV-G", "count" : 59 }
{ "_id" : "GP", "count" : 44 }
{ "_id" : "M", "count" : 37 }
{ "_id" : "Approved", "count" : 5 }
{ "_id" : "AO", "count" : 3 }
{ "_id" : "TV-Y7", "count" : 3 }
{ "_id" : "OPEN", "count" : 1 }
{ "_id" : "Not Rated", "count" : 1 }

本页上的 Node.js 示例使用 Atlas 示例数据集中的 sample_mflix数据库。要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB Node.js驱动程序文档中的入门

要使用MongoDB Node.js驱动程序将 $sortByCount 阶段添加到聚合管道,请在管道对象中使用 $sortByCount操作符。

以下示例创建了一个管道阶段,该阶段根据传入 movie 文档的 rated 字段的值对文档进行分组,然后返回每个组中的文档数量。然后,示例运行聚合管道:

const pipeline = [{ $sortByCount: "$rated" }];
const cursor = collection.aggregate(pipeline);
return cursor;

后退

$sort

在此页面上