对于MongoDB数据库来说可以完成很多MySQL数据库的操作,比如:求和。
我们操作的数据类型的结构:
| 1 | { | 
对于MySQL中的一类求和操作:
| 1 | select by_user, count(*) from mycol group by by_user | 
转换成MongoDB对应的操作的时候就需要使用aggregate聚合操作。
| 1 | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}], { cursor: {} }) | 
上面的情况是对于某个字段做分组然后求和,有时我们只想对某个字段进行全量求和,这个时候_id属性就需要设置为空:
| 1 | db.mycol.aggregate([{$group : {_id : null, num_tutorial : {$sum : "$likes"}}}], { cursor: {} }) | 
如果我们想再加上过滤条件的话就需要使用aggregate的匹配属性:
| 1 | db.mycol.aggregate([{ $match : { by_user: 'runoob.com'} }, {$group : {_id : null, num_tutorial : {$sum : "$likes"}}}], { cursor: { } }) | 
对于新版本(3.6以上)执行以上操作的时候 都需要加上
cursor属性 否则将会报错:The ‘cursor’ option is required
参考阅读:MongoDB 聚合
