Tuesday, 23 May 2017

Group Mongoose documents by date

When I extract data from Mongoose, I use

Collection.find({ isValid: true }).populate(...).then(docs => ...)

I have a date field which is just a normal JavaScript date. I want to group the documents by date, but I want only 2 categories.

The object can be either today (between 00:00 and 23:59 today) or another day. I guess I should use .aggregate().

I have ground this script

Appointments.aggregate([
  {$group: {_id: '$date', patients: {$push: '$patient'}}},
  {$project: {date: '$_id', patients: 1, _id: 0}}
], ...)

so I guess my script should be something like

Collection.aggregate([
  { group: [
    { _id: '$date is today', today: { $push: '$doc' } }
    { _id: '$date is not today', else: { $push: '$doc' } }
  ]},
  { $project: { ... } }
])

I guess this is clever to do with Mongoose, but would it be more efficient to do client-side?



via Jamgreen

No comments:

Post a Comment