mongoose小组结果按年份和月份

对于以下模式(伪代码)。

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

我想返回按月份和年份分组的结果,所以像这样,再次伪代码:

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

我今天早上一直在用Mongoose进行聚合,并且在这个月份和这一年中,这个组合还好,但它并没有返回实际的模型对象。

这是我目前的聚合查询

  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"); }); 

使用$group 累加器运算符来定义超出_id字段。

在这种情况下,您可以使用ROOT系统variables$push来累积每个月份的文档数组:

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

你可以尝试:

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