Syed Is Saqlain
Syed Is Saqlain

Reputation: 380

Count of records by Date MongoDB

Here's a record Customers Collection

 {
    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.

Upvotes: 14

Views: 19004

Answers (5)

Dzone64
Dzone64

Reputation: 108

Mongo actually has a function dateTrunc to do this directly since version 5.0.0

db.getCollection('collectionName').aggregate([
        {
            $group: {
                _id: {
                    $dateTrunc: {
                        date: "$lastModified", unit: "day"
                    }
                },
                count: {$sum: 1}
            }
        }
    ])

Upvotes: 1

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20098

I have counted my date in the following way

Sample Data:

{
    "_id" : ObjectId("5f703ef9db38661df02d3a77"),
    "color" : "black",
    "icon" : "grav",
    "name" : "viewed count",
    "created_date" : ISODate("2020-09-27T07:27:53.816Z"),
    "updated_date" : ISODate("2021-05-11T19:11:14.415Z"),
    "read" : false,
    "graph" : [ 
        {
            "_id" : ObjectId("5f704286db38661df02d3a81"),
            "count" : 1,
            "date" : ISODate("2020-09-27T07:43:02.231Z")
        }, 
        {
            "_id" : ObjectId("5f7043ebdb38661df02d3a88"),
            "date" : ISODate("2020-09-27T07:48:59.383Z"),
            "count" : 2
        }]
}

My query is:

db.test.aggregate(
  [{$match:{"name" : "viewed count"}},
   {$unwind:'$graph'},
    {
      $match: {
        'graph.date': {
          $gt: ISODate("2018-09-27"),
          $lt: ISODate("2021-09-27")
        }
      }
    },
    {
      $project: {
        date: {$dateToString: {format: '%Y-%m-%d', date: '$graph.date'}}
      },
    },
    {
      $group: {
        _id: "$date",
        count: {$sum: 1}
      }
    },
    {
      $sort: {
        _id: 1
      }
    }
  ]
)

output:

[{
    "_id" : "2020-09-27",
    "count" : 58.0
},
{
    "_id" : "2020-09-29",
    "count" : 50.0
}]

Upvotes: 2

Ali Jafari
Ali Jafari

Reputation: 61

This is simpler:

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

Upvotes: 6

danish ali
danish ali

Reputation: 132

I got this sorted in yii2 by this

$aggregateResult = Yii::$app->mongodb->getCollection('patient')->aggregate([
            [
                '$match' => [
                    '$and' => [
                        ['deleted_at' => ['$exists' =>  false]],
                        ['registration_date' => ['$gte' =>  $startDateStamp, '$lte' => $endDateStamp]],
                    ]
                ]
            ],
            [
                '$group' => [
                    '_id' =>  [
                        'day' => ['$dayOfMonth' =>  ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]],
                        'month' => ['$month' => ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]],
                        'year' => ['$year' => ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]]
                    ],
                    'count' => ['$sum' => 1],
                    'date' => ['$first' => ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]]
                ]
            ],

            [
                '$project' => [
                    'date' => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$date']],
                    'count' => 1,
                    '_id' => 0
                ]
            ],
            ['$sort' => ['date' => 1]],

        ]);

Upvotes: 0

Shaishab Roy
Shaishab Roy

Reputation: 16805

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}}})

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
        }
    }
])

Upvotes: 27

Related Questions