$count
階段用于統(tǒng)計(jì)管道中文檔的數(shù)量。
語(yǔ)法
{ $count: <string> }
<string>
是文檔計(jì)數(shù)輸出字段的名稱。<string>
必須是非空字符串,不能以$
開(kāi)頭,也不能包含.
字符。
$count
階段相當(dāng)于下面$group
+$project
聚合序列:
db.collection.aggregate( [
{ $group: { _id: null, myCount: { $sum: 1 } } },
{ $project: { _id: 0 } }
] )
其中myCount
是包含計(jì)數(shù)的輸出字段。也可以為輸出字段指定其他名稱。
舉例
"scores"的集合有以下文檔:
{ "_id" : 1, "subject" : "History", "score" : 88 }
{ "_id" : 2, "subject" : "History", "score" : 92 }
{ "_id" : 3, "subject" : "History", "score" : 97 }
{ "_id" : 4, "subject" : "History", "score" : 71 }
{ "_id" : 5, "subject" : "History", "score" : 79 }
{ "_id" : 6, "subject" : "History", "score" : 83 }
下面的匯總操作分為兩個(gè)階段:
-
$match
階段會(huì)排除分值小于或等于80的文檔,將分值大于80的文檔傳遞到下一階段。 -
$count
階段返回聚合管道中剩余文檔的計(jì)數(shù),并將該值賦值給名為passing_scores
的字段。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-782830.html
db.scores.aggregate(
[
{
$match: {
score: {
$gt: 80
}
}
},
{
$count: "passing_scores"
}
]
)
操作返回以下結(jié)果:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-782830.html
{ "passing_scores" : 4 }
到了這里,關(guān)于MongoDB聚合:$count的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!