nerdexam
MongoDB

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

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: { $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)
  • A
    4% (1)
  • B
    13% (3)
  • C
    75% (18)
  • D
    8% (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

#aggregation pipeline#$group#$sum#compound grouping

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice