nerdexam
MongoDB

C100DBA · Question #70

What does the output x of the following MongoDB aggregation query result into; db.posts.aggregate( [ { $group: { _id; "$author", x: { $sum: $likes } } } ] )

The correct answer is D. Sum of likes on all the posts by an author, grouped by author. D is correct because the $group stage does two things simultaneously: _id: "$author" partitions all documents into separate buckets per author, and x: { $sum: "$likes" } accumulates the total likes within each bucket - giving you a per-author sum of likes. Why the distractors…

MongoDB Fundamentals

Question

What does the output x of the following MongoDB aggregation query result into; db.posts.aggregate( [ { $group: { _id; "$author", x: { $sum: $likes } } } ] )

Options

  • AAverage of likes on all the posts of an author, grouped by author
  • BNumber of posts by an author
  • CSum of likes on all the posts by all the authors
  • DSum of likes on all the posts by an author, grouped by author

How the community answered

(28 responses)
  • A
    11% (3)
  • B
    7% (2)
  • C
    4% (1)
  • D
    79% (22)

Explanation

D is correct because the $group stage does two things simultaneously: _id: "$author" partitions all documents into separate buckets per author, and x: { $sum: "$likes" } accumulates the total likes within each bucket - giving you a per-author sum of likes.

Why the distractors fail:

  • A is wrong because $sum computes a total, not an average - you'd need $avg for that.
  • B is wrong because counting posts requires { $sum: 1 } (increment by 1 per document), not { $sum: "$likes" } (which reads the field value).
  • C is wrong because grouping by "$author" means results are per author, not collapsed into a single total. To sum across all authors at once, you'd set _id: null.

Memory tip: Read a $group stage in two parts - the _id field answers "grouped by what?" and the accumulators answer "computed how, within each group?" Here: grouped by author (_id: "$author") + sum of likes per group ($sum: "$likes") = D.

Topics

#aggregation#$group#$sum#accumulator operators

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice