C100DBA practice question 24 of 25

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?

Full set: 130 questions
Answer options
A: db.population.aggregate( [{ $group: { _id: { state: "$state", city; "$city" },pop: { $sum: 1 > > >] )
B: db.population.aggregate( [{ $group: { _id: { state: Estate", city: "$city" },pop: { $pop: 1 } } }] )
C: db.population.aggregate( [{ $group: { _id: { state: Estate", city: n$city" },pop: { $sum: "$pop" } } }] ) Correct answer
D: db.population.aggregate( [{ $group: { _id: { city: "$city" },pop: { $sum: "$pop" } } }] )Multi Document Transaction is not supported by MongoDB
Correct Answer:
C. db.population.aggregate( [{ $group: { _id: { state: Estate", city: n$city" },pop: { $sum: "$pop" } } }] )
Explanation

This query correctly uses the aggregation framework's $group stage to meet the requirements. It groups documents by a compound id key composed of the state and city fields. The $sum accumulator is then used with the field path "$pop" to calculate the total of the pop field for all documents within each group. This provides the total population for each unique state and city combination. (Note: The provided option contains typos, but its structure is the only one that correctly implements the required logic).

Why Incorrect

A. This option has multiple syntax errors and uses $sum: 1, which counts documents rather than summing the values in the pop field.
B. This option has syntax errors and uses $pop, which is an update operator and not a valid accumulator for the $group stage.
D. This query incorrectly groups only by city, failing to meet the requirement of grouping by both state and city.

References

1. MongoDB Manual, $group (aggregation): "Groups input documents by the specified id expression and for each distinct grouping, outputs a document." (https://www.mongodb.com/docs/manual/reference/operator/aggregation/group/)

2. MongoDB Manual, $sum (aggregation): "Calculates and returns the collective sum of numeric values. $sum ignores non-numeric values." (https://www.mongodb.com/docs/manual/reference/operator/aggregation/sum/)

3. MongoDB University, M121: The MongoDB Aggregation Framework, Chapter 2, "Basic Aggregation - $group and $match". This courseware covers the fundamental usage of $group with a compound id and accumulators like $sum.

Scroll to Top