文档菜单
文档首页
/
MongoDB 手册
/ / /

$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

{ "_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" ] }

以下操作 unwindstags 数组,并使用 $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 }

返回

$sort