Skip to content Skip to sidebar Skip to footer

Mongodb Aggregate Framework - Group By Year

I've been trying to use the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : '$birth_date'}}, tot

Solution 1:

Some versions of Windows have been known to work. By any chance, are you using a 32-bit OS? The code in question is here, and depends upon the gmtime_s() implementation.

If this collection is simply for aggregation queries, you can certainly get by with storing date components in an object. I'd suggest abbreviating the field names (e.g. y, m, d) to save on storage, since the field strings are present in each stored document. The trade-off here is that none of the aggregation date operators can be used. You may want to store the timestamp as a signed integer (e.g. ts) so that you can easily do range queries if necessary.

Solution 2:

This issue is caused by the minimum date not being handled well when aggregated.

A quick workaround (if possible) is to filter the date, either through the ff:

  • Remove the rows with minimum date (via match / filter)
  • Filter through a certain date (greater than x date)

Then aggregate.

Post a Comment for "Mongodb Aggregate Framework - Group By Year"