在上一篇mongodb Aggregation聚合操作之$sort中详细介绍了mongodb聚合操作中的$sort使用以及参数细节。本篇将开始介绍Aggregation聚合操作中的$sortByCount操作。
说明:
根据指定表达式的值对传入文档进行分组,然后计算每个不同组中的文档数。每个输出文档包含两个字段:一个_id字段包含不同的分组值,一个count字段包含属于该分组或类别的文档数。文档按count降序排序。
语法:
{ $sortByCount : < expression > }
备注:$sortByCount阶段等价于下面的$group + $sort序列
{ $group: { _id:
{ $sort: { count: -1 } }
参数讲解:
expression:表达式分组依据。您可以指定除文档文字之外的任何表达式。要指定字段路径,请在字段名称前加一个美元符号$,并将其括在引号中。例如,要按employee字段分组,请指定"$employee"为表达式:{ $ sortByCount : “ $ employee” }
虽然不能为group by expression指定文档文字,但是可以指定计算结果为文档的字段或表达式。例如,如果employee 和business 字段是文档字段,那么下面的$mergeObjects表达式(计算结果为文档)是$sortByCounts的一个有效参数:
{ $sortByCount: { $mergeObjects: [ "$employee", "$business" ] } }
但是,下面这个文档文字表达式的例子是无效的:
{ $sortByCount: { lname: "$employee.last", fname: "$employee.first" } }
1. 示例
初始化数据:
db.sortByCountExample.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展开标签数组,并使用$sortByCount阶段来计算与每个标签关联的文档数量
db.sortByCountExample.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 }