Mongodb Certified Developer Associate C100dev · Free Practice Question Medium
Question 3
A collection called players contains the following documents:
- [
- { _id: 1, user: 'Tom', scores: [ 23, 56, 3, 52, 62 ], bonus: 5 },
- { _id: 2, user: 'Jane', scores: [ 42, 50, 10 ], bonus: 3 }
- ]
You want to add additional fields to each document:
total_score(sum of the scores Array)avg_score(average score in scores Array)total_score_with_bonus(total_score+bonus)
Expected output:
- [
- {
- _id: 1,
- user: 'Tom',
- scores: [ 23, 56, 3, 52, 62 ],
- bonus: 5,
- total_score: 196,
- avg_score: 39.2,
- total_score_with_bonus: 201
- },
- {
- _id: 2,
- user: 'Jane',
- scores: [ 42, 50, 10 ],
- bonus: 3,
- total_score: 102,
- avg_score: 34,
- total_score_with_bonus: 105
- }
- ]
Which query do you need to use?
-
A
- db.players.aggregate([{
- $addFields: {
- total_score: {
- $sum: '$scores'
- },
- avg_score: {
- $avg: '$scores'
- }
- }
- }, {
- $addFields: {
- total_score_with_bonus: {
- $add: ['$total_score', '$bonus']
- }
- }
- }])
-
B
- db.players.aggregate([{
- $addFields: {
- total_score: {
- $sum: 'scores'
- },
- avg_score: {
- $avg: 'scores'
- },
- total_score_with_bonus: {
- $add: ['total_score', '$bonus']
- }
- }
- }])
-
C
- db.players.aggregate([{
- $project: {
- total_score: {
- $sum: '$scores'
- },
- avg_score: {
- $avg: '$scores'
- },
- total_score_with_bonus: {
- $add: ['$total_score', '$bonus']
- }
- }
- }])
-
D
- db.players.aggregate([{
- $add: {
- total_score: {
- $sum: '$scores'
- },
- avg_score: {
- $avg: '$scores'
- }
- }
- }, {
- $add: {
- total_score_with_bonus: {
- $add: ['$total_score', '$bonus']
- }
- }
- }])
Reveal correct answer
Correct answer: A
A.
In this query, we use the $addFields stage to add the desired fields to each document. First, we add the total_score field by using the $sum operator on the scores array. Then, we add the avg_score field by using the $avg operator on the scores array. Finally, we add the total_score_with_bonus field by using the $add operator to add the total_score and bonus fields together.
B.
This query is similar to the correct option, but is missing the $ sign before scores and total_score.
C.
This query uses the $project stage instead of the $addFields stage. The $project stage is used to reshape documents, including selecting specific fields or computing expressions, but it doesn't add new fields to the documents like the $addFields stage does.
D.
The $add stage is used to perform addition between different fields within a document, but it doesn't create new fields. In this case, it attempts to add the total_score and avg_score fields, but since these fields don't exist at that point, the result will be null for both. Therefore, the total_score_with_bonus field will also be null because it depends on the incorrect addition.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
