MongoDB Computed Pattern

Photo by JJ Ying / Unsplash

The Computed Pattern in NoSQL is utilized when we have data that needs to be computed multiple times  and optimize the performance of our app and/or is also used when data reads exceeds writes by a significant amount. For example, let’s say we have a list of Blog Posts with comments.
Each blog post has a comment count, so instead of querying the comment count of each post by using compute pattern we can recalculate the number of comments of the post and store it in a Blog Post document.   This way we save database performance and recalculate the comment count only after comment is created or deleted.
To listen for database updates MongoDB offers change streams or your favorite ODM/ORM should have support for collection/document events. Mongoose calls it middleware .
This pattern allows to save on valueable database resources whenever various calculations need to be read again and again such as view count, averages etc.

Karolis Ščerbiakas

Karolis Ščerbiakas