Stuck with MongoDB? 5 Ways to Keep Analytics Possible

Sometimes the database gets picked before you write a line of code. On my current project, the rest of the company already runs on MongoDB, and no one wants a second stack to maintain. However, we can’t get away from analytics or the need to aggregate data.

Mongo answers those questions fine if the data is shaped for it. It gets painful when you have to rebuild history from whatever the current document says. Here are five habits that have saved me a lot of pain.

Event Collection: Write History Down as It Happens.

For audit purposes, we started out by keeping a collection of events for every main record. It also serves as the activity feed in the UI, and its uses keep growing.

Schema Versions: Old Documents Keep Working.

Mongo doesn’t enforce a schema, which means documents in the old shape and the new shape sit side by side in the same collection. Coming from a heavy Postgres background, that wrecked my brain. Nothing forces a migration, so keeping a version on each document keeps us honest about the shapes in a collection as the codebase grows.

Reason Codes: Use Enums, Not Free Text.

Instead of free text, it was important to use enums. Zod is really helpful here as a layer before the database to flag any unintended changes.

Metrics as Data: Change the Report Without a Deploy.

Because metrics vary from team to team, keep the metric definitions in a collection instead of in the code. This gives you flexibility, and you don’t have to cut a new release for every new column.

Record Early: Do It Before Anyone Asks for the Chart.

It’s much easier to record things before we think we need them. Timestamps on every state change, promised dates next to actual dates, response times. Capturing them up front is far easier than wishing you had.

Mongo will store whatever you give it. Design it to store something you can aggregate, and the reporting questions get a lot less painful. With these habits, MongoDB feels a lot less intimidating for analytics.

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *