C100DBA · Question #12
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: n$city" },pop: { $sum: "$pop" } } }] ). Option C is correct because it properly groups documents by a compound _id containing both "$state" and "$city" field references, and uses { $sum: "$pop" } to correctly accumulate the values of the pop field across each group - satisfying the requirement to calculate population g
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: { $sum: 1 > > >] )
- Bdb.population.aggregate( [{ $group: { _id: { state: Estate", city: "$city" },pop: { $pop: 1 } } }] )
- Cdb.population.aggregate( [{ $group: { _id: { state: Estate", city: n$city" },pop: { $sum: "$pop" } } }] )
- Ddb.population.aggregate( [{ $group: { _id: { city: "$city" },pop: { $sum: "$pop" } } }] )Multi
How the community answered
(24 responses)- A4% (1)
- B13% (3)
- C75% (18)
- D8% (2)
Explanation
Option C is correct because it properly groups documents by a compound _id containing both "$state" and "$city" field references, and uses { $sum: "$pop" } to correctly accumulate the values of the pop field across each group - satisfying the requirement to calculate population grouped by both state and city.
Option A is invalid due to syntax errors: it uses a semicolon instead of a colon (city; "$city") and has a malformed accumulator ($sum: 1 > > >), making it unparseable MongoDB syntax.
Option B fails on two counts: Estate" is missing the $ prefix (field references in MongoDB must be written as "$state"), and $pop is not a valid accumulator operator - the correct operator is $sum.
Option D only groups by city, omitting state from the _id, so it would collapse cities with the same name across different states into a single group - not what the question requires.
Memory tip: In MongoDB $group, think of _id as your "group-by key." To group by multiple fields, wrap them in a sub-document: _id: { field1: "$field1", field2: "$field2" }. Field references always need the $ prefix inside aggregation expressions, and $sum: "$fieldName" sums the field's values (vs. $sum: 1 which just counts documents).
Topics
Community Discussion
No community discussion yet for this question.