Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate by date when a full timestamp is given in aggregation framework?

I have a collection of errors, so that every error carries a date field. How can I aggregate/count/group the errors by DAY only (i.e. exclude the time of the day)? I guess, some smart projection should be applied.

like image 484
BreakPhreak Avatar asked Mar 27 '13 11:03

BreakPhreak


People also ask

Which stages in aggregation framework used to select some specific fields from a collection?

$project − Used to select some specific fields from a collection. $match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.

What is $Not in aggregation?

Definition. Evaluates a boolean and returns the opposite boolean value; i.e. when passed an expression that evaluates to true , $not returns false ; when passed an expression that evaluates to false , $not returns true .

What is unwind in aggregation?

$unwind treats the sizes field as a single element array if: the field is present, the value is not null, and. the value is not an empty array.


1 Answers

You can do this by using the following aggregation operators:

  • $group
  • $year
  • $month
  • $dayOfMonth

This gives you the error count for each date:

db.errors.aggregate(     { $group : {         _id: {             year : { $year : "$date" },                     month : { $month : "$date" },                     day : { $dayOfMonth : "$date" },         },         count: { $sum: 1 }     }} ); 

This example assumes that the date field in your error documents is date and of type BSON Date. There is also a Timestamp type in MongoDB, but use of this type is explicitely discouraged by the documentation:

Note: The BSON Timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.

like image 199
Philipp Avatar answered Nov 10 '22 09:11

Philipp