0
0
MongoDBquery~10 mins

$facet for multiple pipelines in MongoDB - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to use $facet to run multiple pipelines in one aggregation.

MongoDB
db.collection.aggregate([{ $facet: { results: [[1]] } }])
Drag options to blanks, or click blank then click option'
A{ $limit: 5 }
B{ $match: { status: 'A' } }
C{ $sort: { score: -1 } }
D{ $group: { _id: '$status' } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single stage object instead of an array.
Not wrapping the pipeline stages in an array.
2fill in blank
medium

Complete the code to add a second pipeline named 'counts' inside $facet.

MongoDB
db.collection.aggregate([{ $facet: { results: [{ $match: { status: 'A' } }], counts: [[1]] } }])
Drag options to blanks, or click blank then click option'
A{ $sort: { total: -1 } }
B{ $group: { _id: null } }
C{ $limit: 10 }
D{ $count: 'total' }
Attempts:
3 left
💡 Hint
Common Mistakes
Using $group without specifying an accumulator.
Using $sort or $limit instead of $count.
3fill in blank
hard

Fix the error in the $facet stage by completing the missing pipeline for 'averageScore'.

MongoDB
db.collection.aggregate([{ $facet: { averageScore: [[1]] } }])
Drag options to blanks, or click blank then click option'
A{ $group: { _id: null, avgScore: { $avg: '$score' } } }
B{ $match: { score: { $exists: true } } }
C{ $sort: { score: 1 } }
D{ $limit: 1 }
Attempts:
3 left
💡 Hint
Common Mistakes
Using $match instead of $group for aggregation.
Not specifying the _id field in $group.
4fill in blank
hard

Fill both blanks to create two pipelines inside $facet: one for filtering active users and one for counting them.

MongoDB
db.users.aggregate([{ $facet: { activeUsers: [[1]], activeCount: [[2]] } }])
Drag options to blanks, or click blank then click option'
A{ $match: { active: true } }
B{ $count: 'count' }
C{ $group: { _id: '$active' } }
D{ $sort: { name: 1 } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using $group instead of $count for counting.
Not filtering active users before counting.
5fill in blank
hard

Fill all three blanks to create pipelines inside $facet: one to sort by age, one to group by city, and one to count total documents.

MongoDB
db.people.aggregate([{ $facet: { sortedByAge: [[1]], groupedByCity: [[2]], totalCount: [[3]] } }])
Drag options to blanks, or click blank then click option'
A{ $sort: { age: 1 } }
B{ $group: { _id: '$city' } }
C{ $count: 'total' }
D{ $match: { age: { $gt: 18 } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up $group and $count stages.
Not using $sort correctly for ordering.