2013-02-03 18 views
5

如果我的集合看起来像这样,如何获取集合中的全部评论。 (不是每个职位,但总总的意见的收集。)获取集合中的子文档总数

{ 
    _id: 1, 
    post: 'content', 
    comments: [ 
     { 
      name: '', 
      comment: '' 
     } 
    ] 
} 

如果我有立柱A 3组的意见和后B带5层的意见。结果应该是8

回答

12

您可以使用aggregation framework

> db.prabir.aggregate(
    { $unwind : "$comments" }, 
    { $group: { 
     _id: '', 
     count: { $sum: 1 } 
    } 
}) 
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 } 

简而言之这个(临时)创建为每个评论一个单独的文件,然后对每个文件递增count


对于大量的帖子和评论它 可能更有效跟踪的评论数量。当添加评论时,你也增加一个计数器。例如:

// Insert a comment 
> comment = { name: 'JohnDoe', comment: 'FooBar' } 
> db.prabir.update(
    { post: "A" }, 
    { 
     $push: { comments: comment }, 
     $inc: { numComments: 1 } 
    } 
) 

再次使用聚合框架:

> db.prabir.aggregate(
    { $project : { _id: 0, numComments: 1 }}, 
    { $group: { 
     _id: '', 
     count: { $sum: "$numComments" } 
    } 
}) 
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 } 
+0

我是新来的MongoDB。那个简单的代码...是可怕的。 – otocan

8

可以使用aggregation framework为的aggregate方法:

db.test.aggregate(
    // Only include docs with at least one comment. 
    {$match: {'comments.0': {$exists: true}}}, 
    // Duplicate the documents, 1 per comments array entry 
    {$unwind: '$comments'}, 
    // Group all docs together and count the number of unwound docs, 
    // which will be the same as the number of comments. 
    {$group: {_id: null, count: {$sum: 1}}} 
); 

UPDATE

由于MongoDB的2.6的,有做更有效的方法这通过使用$size汇总运算符来直接获得每个doc中的注释数量:

db.test.aggregate(
    {$group: {_id: null, count: {$sum: {$size: '$comments'}}}} 
); 
相关问题