做網(wǎng)站最主要是什么招聘seo專員
$sortByCount
聚合根據(jù)指定表達式的值對輸入文檔進行分組,然后計算每個不同分組中的文檔數(shù)。
每個輸出文檔包含兩個字段:一個是包含不同分組值的_id
字段,另一個是包含屬于該分組或類別的文檔數(shù)量的計數(shù)字段。
文檔按計數(shù)降序排序。
語法
{ $sortByCount: <expression> }
expression
是要分組的表達式,可以指定除文檔字面以外的任何表達式。
如果要指定字段路徑,需要在字段名前加上美元符號$
并用引號引起來,例如,要按employee
字段分組,可指定"$employee"
作為表達式。
{ $sortByCount: "$employee" }
雖然不能為分組表達式指定文檔字面意義,但可以指定一個字段或一個表達式來生成文檔。例如,如果employee
字段和business
字段都是文檔字段,那么$mergeObjects
表達式就可以作為 $sortByCount
的有效參數(shù):
{ $sortByCount: { $mergeObjects: [ "$employee", "$business" ] } }
但是,下面使用文檔字面表達式的示例是錯誤的:
{ $sortByCount: { lname: "$employee.last", fname: "$employee.first" } }
用法
$sortByCount
受100M內(nèi)存使用限制,如果需要額外空間,可以將臨時文件寫入磁盤。
從MongoDB6.0開始,需要100兆內(nèi)存才能執(zhí)行的管道階段會默認將臨時文件寫入磁盤。在 MongoDB 早期版本中,必須傳遞{ allowDiskUse: true}
才能啟用。
單個查找和聚合命令可以通過以下任一方式覆蓋allowDiskUseByDefault
參數(shù):
-
當
allowDiskUseByDefault
設(shè)置為false
時,使用{ allowDiskUse: true}
可以把臨時文件寫入磁盤 -
當
allowDiskUseByDefault
設(shè)置為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
數(shù)組,并使用$sortByCount
階段來計算與每個tag
相關(guān)的文檔數(shù):
db.exhibits.aggregate( [ { $unwind: "$tags" }, { $sortByCount: "$tags" } ] )
操作將返回以下文件,按計數(shù)降序排序:
{ "_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 }