2016-03-05 57 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); 
     }); 
});