2016-02-05 165 views
1

我想用mongodb中的$ avg來計算字段的平均值。 代碼: -

DoctorsReview.aggregate([ 
     { 
      $match: { 
       doctor: doctorsId 
      } 
     }, 
     { 
      $group: { 
      _id: null, 
      averageRating: { $avg: "$rating" }, 
      count: { $sum: 1 } 
      } 
     }],function(error, result){ 
      if(error) 
        console.log(error); 
      console.log(result); 
}); 

的問題是,當我打了第一次查詢,它返回一個空數組,但是當我再次打它,它返回我預計在以前的命中結果。

僅供參考我試圖計算在DoctorsReview模型中對應於doctorsId的評級的平均值。

請幫忙。

DoctorsReview樣本: -

{ 
"_id" : ObjectId("56b473b0b9d8b5b01c6d1529"), 
"rating" : NumberInt(4), 
"review" : "Poor", 
"user" : ObjectId("5673a0e86a8141c00c85a743"), 
"doctor" : ObjectId("56b1cbb4e8e806f8229c1afa"), 
"date" : ISODate("2010-12-12T00:00:00.000+0000"), 
"time" : NumberInt(19), 
"__v" : NumberInt(0) 
} 

預期的響應: -

[{ _id: null, averageRating: 4, count: 1}]; 

所以當我打的第一次,我得到空數組作爲迴應,但是當服務器再次襲來,我得到了預期的迴應。

回答

0

請在下面嘗試,我沒試過。

{ 
     $match: { 
      doctor: doctorsId 
     } 
    }, 
    { 
     $group: { 
     _id: null, 
     averageRating: { $avg: "$rating" }, 
     count: { $sum: 1 } 
     } 
    },{$project:{_id:0, rating:"$averageRating", __v:"$count"}}