按日期 MongoDB 的记录数 [英] Count of records by Date MongoDB

查看:41
本文介绍了按日期 MongoDB 的记录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个记录客户集合

 {
    name: xyz,
    .
    .
    .
    createdAt: Sun Nov 20 2016 00:00:00 GMT+0530 (IST)
    lastModified: Sat Dec 10 2016 00:00:00 GMT+0530 (IST)
 }

我需要能够根据日期修改客户数量

I need to be able to get count of customers modified based on date

eg: Date                Count(lastModified)
    11-20-2016           10
    12-20-2016            7
    13-20-2016            9

我希望结果像这样分组.

I want the result grouped something like this.

推荐答案

如果你想按lastModified日期和时间来统计,那么可以像这样使用:

if you want to count by lastModified date and time then can use just like:

db.getCollection('collectionName').aggregate({$group:{_id: "$lastModified", count:{$sum:1}}})

如果你想按 lastModified date only 来计数,那么可以像这样使用:

and if you want to count by lastModified date only then can use just like:

db.getCollection('collectionName').aggregate(
[
    {
        $group:
        {
            _id:
            {
                day: { $dayOfMonth: "$lastModified" },
                month: { $month: "$lastModified" }, 
                year: { $year: "$lastModified" }
            }, 
            count: { $sum:1 },
            date: { $first: "$lastModified" }
        }
    },
    {
        $project:
        {
            date:
            {
                $dateToString: { format: "%Y-%m-%d", date: "$date" }
            },
            count: 1,
            _id: 0
        }
    }
])

这篇关于按日期 MongoDB 的记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆