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…
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)- A11% (3)
- B7% (2)
- C4% (1)
- D79% (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
$sumcomputes a total, not an average - you'd need$avgfor 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
Community Discussion
No community discussion yet for this question.