MongoDB聚合: $sortByCount

$sortByCount聚合根据指定表达式的值对输入文档进行分组,然后计算每个不同分组中的文档数。

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

文档按计数降序排序。

语法

{ $sortByCount:  <expression> }

expression是要分组的表达式,可以指定除文档字面以外的任何表达式。

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

{ $sortByCount:  "$employee" }

虽然不能为分组表达式指定文档字面意义,但可以指定一个字段或一个表达式来生成文档。例如,如果employee字段和business字段都是文档字段,那么$mergeObjects表达式就可以作为 $sortByCount的有效参数:

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

但是,下面使用文档字面表达式的示例是错误的:

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

用法

$sortByCount受100M内存使用限制,如果需要额外空间,可以将临时文件写入磁盘。

从MongoDB6.0开始,需要100兆内存才能执行的管道阶段会默认将临时文件写入磁盘。在 MongoDB 早期版本中,必须传递{ allowDiskUse: true}才能启用。

单个查找和聚合命令可以通过以下任一方式覆盖allowDiskUseByDefault参数:

  • allowDiskUseByDefault设置为false时,使用{ allowDiskUse: true}可以把临时文件写入磁盘

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

$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" ] }

以下操作会展开tags数组,并使用$sortByCount阶段来计算与每个tag相关的文档数:

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 }

你可能感兴趣的:(mongodb,mongodb,数据库)