0

I'm looking to create a timeline REST api which will pull MongoDB data entries and organize them using a created_at property that I have in the collection.

I'm looking to separate the "timeline" entries by a few different groupings.

The first grouping will be "last 24 hours", the second grouping will be "yesterday", the third grouping will be "last week", and the final grouping will be "everything else". I will limit the "everything else" so it doesn't pull a bunch of things from a long time ago...

What I'm doing in Mongoose is a MongoDB $group to group by my created_at, but I'm having a problem because I simply want to do a created_at "like" because I can't use the exact timestamp or the grouping won't work.

Does anyone have any experience with something similar? I'd how can this be expanded to use multiple groupings where I can first group by "today" (last 24 hours) and then group everything else by week or "last week"?

I need to first do a group, then exclude the previous grouped results in my next grouping.

Thanks for your time.

  • 1
    you're going to want an addfields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/#pipe._S_addFields in your pipeline adding a new field with the date operator to include YYYY-DayOfYear and another for YYYY-WeekOfYear. https://docs.mongodb.com/manual/reference/operator/aggregation-date/ Then you group based on those two new added fields – bauman.space May 22 '17 at 16:34
  • You can use `$facet`. You will need to combine both `$facet` [example](https://stackoverflow.com/questions/43950745/mongo-mongoose-aggregation-redact-and-cond-issues/43989659#43989659) & `$group` by [range](https://stackoverflow.com/questions/43889978/mongoose-how-to-write-a-query-with-if-condition/43959932#43959932) example. – s7vr May 22 '17 at 21:58

1 Answers1

0

Why don't you separate it into three queries? First query for today:

   var today = new Date();
   var startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate());
   MyModel.find({created_on: {$gte: startOfToday}}, function (err, docs) { ... });

Second query for yesterday:

   var yesterday = new Date();    
   yesterday = yesterday.setDate(today.getDate() - 1);
   var startOfYesterday = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate());
   MyModel.find({created_on: {$gte: startOfYesterday, $lt: startOfToday}}, function (err, docs) { ... });

Third query for anything else:

   MyModel.find({created_on: {$lt: startOfYesterday}}, function (err, docs) { ... });
Toan Tran
  • 1,937
  • 1
  • 24
  • 37