Lee Brindley
Lee Brindley

Reputation: 6482

Mongoose group results by year and month

For the following schema (pseudo code).

var Post = {
     title: "",
     content: "",
     date: new Date()
}

I want to return results grouped by month & year, so something like so, again psuedo code:

 [
   { year: "2016", 
     month: "4", 
     results: [ 
         {_id: "1232", title: "foo", content: "bar", date: "Some date" }, 
         {_id: "1232", title: "foosdas", content: "barsdasda", date: "Some other date" } ] }
 ]

I've been trying aggregation with Mongoose this morning and that groups by the month and year just fine, It doesn't return the actual model objects though.

This is my current aggregate query

               Post
                .aggregate({
                    $group: {
                        _id : { year: { $year : "$date" }, month: { $month : "$date" }},
                    }
                })
                .exec(function (error, items) {
                    if (error) { return next(error); }

                    console.log(items);
                    res.append("x-count", count);
                    return res.json("Done");
                });

Upvotes: 2

Views: 2399

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311895

Use accumulator operators in your $group to define fields beyond _id.

In this case, you would use $push with the ROOT system variable to accumulate the array of docs from each month:

Post.aggregate([{
    $group: {
        _id : { year: { $year : "$date" }, month: { $month : "$date" }},
        results: {$push: '$$ROOT'}
    }
}).exec(...

Upvotes: 4

Marko vlaić
Marko vlaić

Reputation: 316

you could try:

mongoose.model('yourCollection').find({year:'2016',month:'4'},function(err,results){
    //your code here
});

Upvotes: -2

Related Questions