Event Sourcing System — NoSQLVerse Project
Event Sourcing System — NoSQLVerse Project: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 97 of 100
Event Sourcing System
Foundations & CRUD ✓ → Queries & Schema ✓ → Aggregation & Scale ✓ → Atlas & Projects
Atlas & Projects · 4 — Build · ~10 min · MongoDB — Real-World Projects
What is this?
Event sourcing stores every state change as an immutable event (OrderCreated, ItemAdded). Current state is rebuilt by replaying events or reading a materialized projection collection.
Why should you care?
Auditable domains — finance, healthcare workflows, inventory — need “what happened” not only “what is”.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.orderEvents.insertMany([
{ streamId: "ord-1", version: 1, type: "OrderCreated", data: { userId: "u1" }, at: new Date() },
{ streamId: "ord-1", version: 2, type: "ItemAdded", data: { sku: "TV-55", qty: 1 }, at: new Date() },
{ streamId: "ord-1", version: 3, type: "OrderPaid", data: { amount: 42999 }, at: new Date() }
])
db.orderEvents.createIndex({ streamId: 1, version: 1 }, { unique: true })
// Projection:
db.orderState.updateOne(
{ _id: "ord-1" },
{ $set: { userId: "u1", items: [{ sku: "TV-55", qty: 1 }], status: "paid", amount: 42999 } },
{ upsert: true }
)
db.orderEvents.find({ streamId: "ord-1" }).sort({ version: 1 })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- orderEvents is append-only with unique streamId+version.
- orderState is a projection for fast reads.
- Replaying events rebuilds state if projections corrupt.
- Never update old events — append compensating ones.
Practice next
- Insert the three events.
- Build/update the projection document.
- Query the event stream in version order.
- Rebuild orderState from scratch by folding events in a script.
- Watch orderEvents with change streams to update projections.
Remember
Append immutable events per stream. Project current state separately. Unique (streamId, version) is critical.
Ledger-grade order audit
Support replays ord-1 events to see exactly when an item was added and paid.
Outcome: Disputes resolve with a full timeline, not a guess.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!