2016-04-11 37 views
2

对于下面的模式(伪代码)。猫鼬组的结果按年份和月份

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" } ] } 
] 

我一直在努力聚集和一年好,它不会返回实际的模型对象。

这是我目前的汇总查询

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

你能忍受,你得和原来的文件呢? – BanksySan

回答

-2

你可以尝试:

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

哪里是你想要匹配条件的领域????? –

0

使用accumulator运营商在$group定义超越_id领域。

在这种情况下,你可以使用$pushROOT系统变量从各月累计文档的数组:

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