Mongodb提供了一些聚合的接口,以方便用户查询表并返回计算后的结果。 本文主要是记录一些常用的聚合以方便查阅。 常见的操作有sum, count, average,group等等。以上操作又可以用管道聚合在一起:

::

db.collection.aggregrate([
   pipe1_operator : {....},
   pipe2_operator : {....},
   pipe3_operator : {....}
])

Mongo提供了多种管道操作符,例如$match, $group, $project, $limit, $skip, $sort等, 更多关于Mongo管道可以查阅 官方文档 <https://docs.mongodb.com/manual/core/aggregation-pipeline/>_.

举个例子,创建一个下面的schema:

::

var isd_schema = mongoose.Schema({}, {
    strict: false,
    collection: 'isds'
});
var isd_model = conn.model('isds', isd_schema);

.. _$group:

$group ^^^^^^ 计算属于某个地区的用户数量

::

isd.aggregate([
        {
            $group: {
                _id: '$region',  //$region 是表的列名
                count: {$sum: 1}
            }
        }
    ], function (err, result) {
        if (err) {
            next(err);
        } else {
            res.json(result);
        }
    });

.. _$match:

$match ^^^^^^

$match表示符合条件的条目。 下面查询表示上个月加入的用户:

::

var time = new Date().getTime() - 30 * 24 * 60 * 60 * 1000;
    isd.aggregate([
        {
            $match: {
                created: {$gt: new Date(time)}
            }
        },
        {
            $group: {
                _id: null,
                count: {$sum: 1}
            }
        }
    ], function (err, result) {
        if (err) {
            next(err);
        } else {
            res.json(result);
        }
    });

.. _$project:

$project ^^^^^^^^

$project用于动态加入新的行,类似于sql的select something as *otherthing* ,并且这新的行可以 用于更进一步的聚合操作。

以下查询表示每月注册的用户数量 ::

isd.aggregate([
        {
            $project: {
                month: {$month: "$created"}
            }
        }, {
            $group: {
                _id: "$month",
                users: {$sum: 1}
            }
        }
    ], function (err, result) {
        if (err) {
            next(err);
        } else {
            res.json(result);
        }
    });