2016-03-05 59 views
-1

計算集合中的所有子文檔在這裏,我需要用貓鼬如何使用貓鼬

這是我的路線來計算集合中的所有子文件

router.get('/all-booking', function(req, res){ 
     BookingList.find({}, 'booking', function (err, docs) { 
      if(err) 
       throw err; 
      res.json(docs); 
     }); 
    }); 

在這裏BookingListbookingsubdocument array,通過上面的查詢得到Collection中的所有子文件,但是我需要Count所有的子文件,我該怎麼做。

幫助將不勝感激

+0

嗯。 docs.length? –

+0

它顯示我的記錄長度,沒有子文件數 –

+0

啊我的壞..... –

回答

0

使用聚合得到計數:

router.get('/all-booking', function(req, res){ 
    var pipeline = [ 
     { // Get the length of the booking array 
      "$project": { 
       "booking_size": { "$size": "$booking" } 
      } 
     }, 
     { // Get the total length of all the booking fields 
      "$group": { 
       "_id": null, 
       "count": { "$sum": "$booking_size" } 
      } 
     } 
    ] 
    BookingList.aggregate(pipeline, function (err, result) { 
     if(err) 
      throw err; 
     console.log(result[0].count); // Prints the count of all the booking sub-documents in the collection 
     res.json(result); 
    }); 

    // Or using the fluent aggregate pipeline builder API 
    BookingList.aggregate() 
     .project({ "booking_size": { "$size": "$booking" } }) 
     .group({ "_id": null, "count": { "$sum": "$booking_size" } }) 
     .exec(function (err, result) { 
      if(err) 
       throw err; 
      console.log(result[0].count); // Prints the count of all the booking sub-documents in the collection 
      res.json(result); 
     }); 
});