Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of records by Date MongoDB

Tags:

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.

like image 775
Syed Is Saqlain Avatar asked Dec 15 '16 06:12

Syed Is Saqlain


People also ask

How do I count rows in MongoDB?

count() method is used to return the count of documents that would match a find() query. The db. collection. count() method does not perform the find() operation but instead counts and returns the number of results that match a query.

What is $project in MongoDB?

Definition. $project. Passes along the documents with the requested fields to the next stage in the pipeline. The specified fields can be existing fields from the input documents or newly computed fields.


1 Answers

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
        }
    }
])
like image 80
Shaishab Roy Avatar answered Nov 16 '22 04:11

Shaishab Roy