MongoDB aggregate match count

MongoDB aggregate match count

MongoDB 中,aggregate 的 match count 操作返回包含符合的文档的计数,理解为返回与表或视图的 find() 查询匹配的文档的计数。

MongoDB match count详解

语法

db.collection.aggregate( [ { $group: { _id: null, myCount: { $count: 1 } } }, { $project: { _id: 0 } } ] )

说明

这里 myCount 自定义,相当于 mysql 的 select count(*) as myCount。

案例

我们首先,使用 mongo 命令,连接上数据库,具体命令如下:

mongo

如下图所示:

05_mongodb aggrate count.png

现在,我们使用 use 命令,切换到 haicoder 数据库,具体命令如下:

use haicoder

现在,我们使用 insert 插入三条记录,具体命令如下:

db.articles.insert([ { "url" : "haicoder.net/cpp", "score":100, "views" :10000 }, { "url" : "haicoder.net/golang", "score":90, "views" :20000 }, { "url" : "haicoder.net/java", "score":95, "views" :1000 } ]);

执行完毕后,此时,如下图所示:

06_mongodb aggrate count.png

我们看到,此时提示我们成功插入了三条记录,现在,我们使用 aggregate count,查询总记录数,具体命令如下:

db.articles.aggregate([ {$match: { score: { $gt: 90 } }}, {$count:"passing_scores" } ]);

执行完毕后,此时,如下图所示:

07_mongodb aggrate count.png

我们看到,此时返回了合法的记录的条数。

MongoDB aggregate match count总结

在 MongoDB 中,aggregate 的 match count 操作返回包含符合的文档的计数,理解为返回与表或视图的 find() 查询匹配的文档的计数。