2014-01-10 90 views
1

我正在嘗試貓鼬聚集。我想獲得日期範圍內的字段總數。 http://mongoosejs.com/docs/api.html#model_Model.aggregate日期範圍內的貓鼬聚集

mymodel.aggregate({$match:{date:{$gte: fromDate, $lt: toDate}}}, 
        {$project:{_id:0,date:1, count:1}}, 
        {$group:{'_id':0,count:"$count"}}).exec(function(err,data){ 
     if(err){ 
      console.log('Error Fetching model'); 
      console.log(err); 
     } 
     callback(false, data); 
}); 

這是行不通的。

{ [MongoError: exception: the group aggregate field 'count' must be defined as an expression inside an object] 
    name: 'MongoError', 
    errmsg: 'exception: the group aggregate field \'count\' must be defined as an expression inside an object', 
    code: 15951, 
    ok: 0 } 

任何想法?

回答

2

這個語法是不正確的:

{$group:{'_id':0,count:"$count"}} 

$count是不是在上述運營商,而只是一個字段引用。您不能在$group中擁有「裸體」字段參考。您需要使用聚合操作,就像在:

{$group:{'_id':0,count:{"$sum": "$count"}}} 

請出示了一些簡單的文件,我可以在一個更復雜的方式更新了答案。

+0

謝謝:)它工作:) – Neo