2016-04-11 34 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(...