Wednesday 24 May 2017

Group documents by month in MongoDB

Right now I have a Mongoose query which looks something like

Collection
  .find( selector )
  .sort( sortCriteria )
  .select( selectCriteria )
  .populate( populateCriteria1 )
  .populate( populateCriteria2 )
  .then( docs => ... )
  .catch( errHandler )

So I am doing quite a lot in my query.

Each document in my collection has a date. I want the documents returned grouped by month and year. So it should become something like

docs = [
  { _id: { year: 2017, month: 4 }, docs: [ ... ] },
  { _id: { year: 2017, month: 5 }, docs: [ ... ] },
  { _id: { year: 2017, month: 6 }, docs: [ ... ] }
]

I guess this is a simple .aggregate(), but I am not sure where I should include it since I am doing filtering using .find(), sorting using .sort(), field selection using .select(), and populates using .populate().

Each document has the field date, so it might be something like

Collection
  .find( selector )
  .aggregate([
    { $project: { month: { $month: $date }, year: { $year },
    { $group: { _id: { $month: $date, $year: $date }, docs: { $push: '' } }
  ])



via Jamgreen

No comments:

Post a Comment