Menu

Post image 1
Post image 2
Post image 3
Post image 4
Post image 5
Post image 6
Post image 7
Post image 8
Post image 9
Post image 10
1 / 10
0

MongoDB `$facet` Explained: One Query, Multiple Results

DEV Community: mongodb·VisuaLeaf·3 days ago
#SmjdNEkp
#dev#payments#facet#paid#method#aggregation
Reading 0:00
15s threshold

Sometimes one MongoDB aggregation needs to return more than one result. For example, from the same payments collection, you may want revenue by payment method, total revenue, and the latest paid payments. You could write separate aggregations for each one. But $facet lets you keep them in the same pipeline. It takes the same input documents and sends them through smaller pipelines. Each one returns its own result. That is why $facet is useful for dashboards, reports, filters, and analytics pages. MongoDB describes $facet as a way to run multiple aggregation pipelines in one stage on the same input documents. You can read more in the official MongoDB documentation . The Payments Example For this example, we will use a payments collection.onA document may look like this: { amount : 120 , method : " card " , currency : " USD " , status : " paid " , paidAt : " 2026-05-20T10:30:00Z " } Enter fullscreen mode Exit fullscreen mode Let’s say you want a small report on paid payments.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More