0

Here is an example MongoDB collection of articles with embedded comments:

{
  _id: 1,
  name: "article_1",
  comments: [
    { title: 'title_1_1', ... },
    { title: 'title_1_2', ... }
  ]
}
{
  _id: 2,
  name: "article_2",
  comments: [
    { title: 'title_2_1', ... },
    { title: 'title_2_2', ... },
    { title: 'title_2_3', ... }
  ]
}

How can I efficiently query for the total count of comments? The result should be 5 for the example above.

dasboe
  • 275
  • 1
  • 2
  • 13
  • The title and the question appear to be slightly different, so you basically get both answers. `.aggregate([{ "$match": { "comments.5": { "$exists": true } } },{ "$group": { "_id": null, "count": { "$sum": { "$size": "$comments" } } }}])`. Or just `.find({ "comments.5": { "$exists": true } })` if you only wanted to return the documents that have more than 5 comments. Array notation is `n-1` so `.5` means there are at least 6 elements. – Neil Lunn Mar 29 '19 at 12:30
  • I'm sorry for the duplication and for the confusing question. I edited it so it's hopefully clear now. The answer I was looking for is aggregate({ $group: { _id: null, totalComments: { $sum: { $size: "$comments" } }. The first "question already answered" link above helped! – dasboe Mar 29 '19 at 12:49

0 Answers0