nerdexam
MongoDB

C100DBA · Question #34

Consider that you have a collection called population which has fields state and city. Which of the following query will calculate the population grouped by state and city?

The correct answer is C. db.population.aggregate( [{ $group: { _id: { state: Estate", city: "$city" },pop: { $sum: "$pop" } } }] ). Option C is correct because it properly groups documents by both state and city using a compound _id object, and uses the $sum accumulator to total the pop field across each group - the only combination that satisfies what the question asks for. A is wrong because $pop is an…

MongoDB Fundamentals

Question

Consider that you have a collection called population which has fields state and city. Which of the following query will calculate the population grouped by state and city?

Options

  • Adb.population.aggregate( [{ $group: { _id: { state: "$state", city: "$city" },pop: { $pop: 1 } } }] )
  • Bdb.population.aggregate( [{ $group: { _id: { city: "$city" },pop: { $sum: "$pop" } } }] )Multi
  • Cdb.population.aggregate( [{ $group: { _id: { state: Estate", city: "$city" },pop: { $sum: "$pop" } } }] )
  • Ddb.population.aggregate( [{ $group: { _id: { state: Estate", city: "$city" },pop: { $sum: 1 > > >] )

How the community answered

(30 responses)
  • A
    3% (1)
  • B
    3% (1)
  • C
    80% (24)
  • D
    13% (4)

Explanation

Option C is correct because it properly groups documents by both state and city using a compound _id object, and uses the $sum accumulator to total the pop field across each group - the only combination that satisfies what the question asks for.

  • A is wrong because $pop is an array update operator, not a valid aggregation accumulator. The correct accumulator to sum a numeric field is $sum.
  • B is wrong because it only groups by city, omitting state - so totals would collapse across states, giving you incorrect cross-state city aggregations.
  • D is wrong due to a syntax error: $sum: 1 > > >] is malformed. $sum: 1 counts documents rather than summing the pop field, and the broken brackets make it invalid regardless.

Memory tip: When grouping by multiple fields in MongoDB $group, think of _id as your "group key" - pass it an object with each field you want to group by (e.g., { state: "$state", city: "$city" }), and always use $sum: "$fieldName" (with the $ prefix) to total an existing numeric field rather than just counting.

Topics

#aggregation#$group#$sum#pipeline

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice