获取集合中的子文档总数

pra*_*bir 6 mongodb

如果我的集合看起来像这样,我如何获得集合中的总评论.(不是每篇帖子的总评论数,而是该集合的总评论数.)

{
    _id: 1,
    post: 'content',
    comments: [
        {
            name: '',
            comment: ''
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

如果我发布A有3条评论,发布B有5条评论.结果应该是8.

Jus*_*ase 14

您可以使用聚合框架:

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

简而言之,这(暂时)为每个注释创建一个单独的文档,然后count为每个文档递增.


对于大量的帖子和评论,跟踪评论的数量可能更有效.添加注释时,您还会增加一个计数器.例:

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

再次使用聚合框架:

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

  • 我是mongodb的新手。那个简单的代码……太可怕了。 (2认同)

Joh*_*yHK 9

您可以使用聚合框架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}}}
);
Run Code Online (Sandbox Code Playgroud)

UPDATE

从MongoDB 2.6开始,通过使用$size聚合运算符直接获取每个文档中的注释数量,有一种更有效的方法:

db.test.aggregate(
  {$group: {_id: null, count: {$sum: {$size: '$comments'}}}}
);
Run Code Online (Sandbox Code Playgroud)