user3210860
user3210860

Reputation: 3

MongoDB beginner - Group by date

Just starting with mongodb and used this post to do a similar query but I need the actual date like mm/dd/yyyy instead of just the day of year - help!

How to group by multiple fields in MongoDB when one is a date field

Here is the query I have (almost the same as the post above):

db.col.aggregate(
    { $group: { 
        _id: { 
            status: "$status", 
            dayOfYear: { $dayOfYear: "$datetime" }
        },
        hits: { $sum: "$hits" } 
    } }
)

Here is sample data:

{
    "_id" : ObjectId("45f5ed29f4e1a522bfe53f13"),
    "hits" : 2,
    "status" : 400,
    "datetime" : ISODate("2014-01-10T10:17:57.216Z")
}

Upvotes: 0

Views: 146

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

You can add more date columns or remove them to get different groupings:

db.col.aggregate(
    { $group: { 
        _id: { 
            status: "$status", 
            month: { $month: "$datetime" },
            day: { $dayOfYear: "$datetime" },
            year: { $year: "$datetime" }
        },
        hits: { $sum: "$hits" } 
    } }
)

What this means is: for each unique status that appeared on a particular day (ignore time) sum up all hits.

Upvotes: 1

Related Questions