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…
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)- A3% (1)
- B3% (1)
- C80% (24)
- D13% (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
$popis 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, omittingstate- 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: 1counts documents rather than summing thepopfield, 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
Community Discussion
No community discussion yet for this question.