Mongodb Certified Developer Associate C100dev · Free Practice Question Medium
Question 2
Consider the following MongoDB collection students:
- {
- "_id": 1,
- "name": "John Doe",
- "age": 25,
- "class": "A"
- },
- {
- "_id": 2,
- "name": "Jane Doe",
- "age": 22,
- "class": "B"
- },
- {
- "_id": 3,
- "name": "Jim Smith",
- "age": 24,
- "class": "A"
- }
What is the query to find the average age of all students in class "A"?
-
A
- db.students.find({class: "A"}).avg("age")
-
B
- db.students.find({class: "A"}).mean("age")
-
C
- db.students.aggregate([
- { $match: { class: "A" } },
- { $group: { _id: null, avg_age: { $avg: "$age" } } }
- ])
-
D
- db.students.aggregate([
- { $match: { class: "A" } },
- { $group: { _id: "$class", avg_age: { $avg: "$age" } } }
- ])
Reveal correct answer
Correct answer: C
A.
The avg() method is not applicable in the find() method. The avg() method is used in the aggregation pipeline to calculate the average value, but not directly in the find() method.
B.
The mean() method is not applicable in the find() method. The mean() method is used in the aggregation pipeline to calculate the mean value, but not directly in the find() method.
C.
It uses the aggregation framework to filter the documents using the $match stage and find the students with class "A". Then, the $group stage groups all the documents into a single group (null) and calculates the average age using the $avg aggregation operator. This pipeline will provide the desired output of the average age of students in class "A".
D.
Although it correctly filters the documents using the $match stage to find the students with class "A", it groups the documents by the class field in the $group stage, which means it will provide the average age for each distinct class, not the average age of students in class "A".
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
