$sortByCount (aggregation)

在本页面

Definition

  • $sortByCount
    • 3.4 版的新功能。

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

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

文档按count降序排序。

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

{ $sortByCount:  <expression> }
FieldDescription
expressionExpression分组。您可以指定除文档 Literals 之外的任何表达式。

要指定field path,请在字段名前加上美元符号$并将其括在引号中。例如,要按字段employee分组,请将"$employee"指定为表达式。
{ $sortByCount: "$employee" }
尽管不能为表达式指定组的文档 Literals,但是,可以指定对文档求值的字段或表达式。例如,如果employeebusiness字段是 document 字段,则下面的$mergeObjects表达式(对文档求值)是$sortByCounts的有效参数:
{ $sortByCount: { $mergeObjects: [ "$employee", "$business" ] } }
但是,下面带有文档 Literals 表达式的示例无效:
{ $sortByCount: { lname: "$employee.last", fname: "$employee.first" } }

Behavior

$sortByCount阶段等效于以下$group $sort序列:

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

Example

考虑包含以下文档的集合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" ] }

以下操作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 }