14

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.

2

5 Answers 5

27

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
        }
    }
])
Sign up to request clarification or add additional context in comments.

Comments

6

This is simpler:

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

Comments

2

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

Comments

1

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

Comments

0

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]],

        ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.