DEV Community

Cover image for Delightful Database Design - Mastering MongoDB Queries - Series #11

Delightful Database Design - Mastering MongoDB Queries - Series #11

functional_js profile image Functional Javascript ・2 min read


AF = Aggregation Framework


We've covered a lot of powerful features of shaping data that we retrieve from the database, but we've also barely scratched the surface.

Other powerful data manipulation actions we can do:

  • joins (using the $lookup operator)
  • writing results to new collections (using the $out operator)
  • performing unions on dataset (using the $unionAll operator)
  • merging datasets (using the $merge operator)

These are all "stage operators". They are stages of our aggregation pipeline, which is our full query, and is represented as an arr of stages. Each stage is a single atomic unit of our database query.

Here is some pseudocode to understand the structure of composing the database query:

const aggregationPipeline = [
 { $stage1 },
 { $stage2 },
 { $stage3 },
Enter fullscreen mode Exit fullscreen mode

Then we simply make the call to the database using the "aggregate" func.
The aggregate func takes one parameter, the aggregation pipline arr; which is simply an arr of objs called stages.
That's all there is to the "MongoDB Aggregation Framework" (AF) from the bird's eye view:

return await client.db(dbName).collection(collName).aggregate(aggregationPipeline).toArray();
Enter fullscreen mode Exit fullscreen mode

Question and Answer

How does AF compare with other database query systems, like Mongoose or GraphQL.

AF vs Mongoose:

The AF is well beyond the capability of Mongoose.
When you're composing AF queries, you're writing queries directly for the MongoDB engine and optimizer. It natively understands the query and optimizes it. AF is the future direction of the MongoDB company and ecosystem. They are pouring tens of thousands of development and research hours into it to make it better every iteration.

AF vs GraphQL:

These are two different products.
For example, your GraphQL resolvers can use the AF to retrieve data. GraphQL has it's set of usecases that it is designed for, like bringing various (or disparate) datastores together into a coherent and consistent orchestration.
AF is deceptively simple; But also deceptively powerful and performant. So unless your enterprise usecase calls for a GraphQL-style solution, you may be better off selecting the least amount of moving parts.

What's Next?

In the next few series of articles, we'll do some advanced and creative data-shaping activities. Taking the AF approach makes this possible.

Discussion (1)

Forem Open with the Forem app