mongo Aggregation group

来源:互联网 发布:java 内存管理 编辑:程序博客网 时间:2024/05/22 14:34

按年/月进行统计:

db.node.aggregate([{$group:{_id: {    year : { $year : "$publishedDate" },                            month : { $month : "$publishedDate" }},count: {$sum: 1}}},{$sort: {"_id": 1}}]);

得到如下结果:

{        "result" : [                {                        "_id" : {                                "year" : 2013,                                "month" : 3                        },                        "count" : 1                },                {                        "_id" : {                                "year" : 2013,                                "month" : 4                        },                        "count" : 14                }        ],        "ok" : 1}

如果只按年统计,则把条件中的月去掉即可,
db.node.aggregate([{$group:{_id: {    year : { $year : "$publishedDate" }},count: {$sum: 1}}},{$sort: {"_id": 1}}]);

对符合特定条件的结果,进行分组:

db.user.aggregate([{ $match : { "createDate" : { $gte : new ISODate("2015-01-01T20:15:31Z") } } },{$group:{_id: {year : { $year : "$createDate" },                   <span style="white-space:pre"></span>month : { $month : "$createDate" }},count: {$sum: 1}}},{$sort: {"_id": 1}}]);

即可对2015-01-01之后的用户进行分组统计,结果:
{        "result" : [                {                        "_id" : {                                "year" : 2015,                                "month" : 1                        },                        "count" : 1                },                {                        "_id" : {                                "year" : 2015,                                "month" : 2                        },                        "count" : 6                }        ],        "ok" : 1}


还有,
db.log.aggregate([{ $match : { action : "login" } },{$group:{_id: {year : { $year : "$datetime" },                    <span style="white-space:pre"></span>month : { $month : "$datetime" }},count: {$sum: 1}}},{$sort: {"_id": 1}}]);


0 0
原创粉丝点击