外贸网站装修,长春建站方案,罗湖网站开发,长春谁家做网站$sortByCount聚合根据指定表达式的值对输入文档进行分组#xff0c;然后计算每个不同分组中的文档数。
每个输出文档包含两个字段#xff1a;一个是包含不同分组值的_id字段#xff0c;另一个是包含属于该分组或类别的文档数量的计数字段。
文档按计数降序排序。
语法
{…$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 : OKeefe, 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 }