All projects
Banking System
Accounts, transfers with ACID transactions, and an immutable ledger.
Schema design
accounts
Current balance is stored (computed pattern) and protected by transactions.
accounts document
{
_id: "ACC-10023",
ownerId: ObjectId(),
type: "checking",
balance: NumberDecimal("2500.75"),
currency: "USD",
status: "active"
}ledger
Append-only double-entry ledger. Never updated, never deleted — the source of truth for audits.
ledger document
{
_id: ObjectId(),
txId: "TX-88831",
entries: [
{ account: "ACC-10023", amount: NumberDecimal("-100.00") },
{ account: "ACC-20551", amount: NumberDecimal("100.00") }
],
reason: "transfer",
at: ISODate()
}Key queries
Account balance
mongosh
db.accounts.findOne({ _id: "ACC-10023" }, { balance: 1 })Statement (ledger entries touching an account)
mongosh
db.ledger.find({ "entries.account": "ACC-10023" })
.sort({ at: -1 }).limit(50)Indexes
db.ledger.createIndex({ "entries.account": 1, at: -1 })Statements query by account and time — multikey index on the embedded entries.
db.accounts.createIndex({ ownerId: 1 })List all accounts belonging to a customer.
Aggregations
Recompute a balance from the ledger (audit)
mongosh
db.ledger.aggregate([
{ $unwind: "$entries" },
{ $match: { "entries.account": "ACC-10023" } },
{ $group: { _id: null, balance: { $sum: "$entries.amount" } } }
])Performance tips
- 1.Money movement MUST use a multi-document transaction: debit account, credit account, insert ledger entry — all or nothing.
- 2.Use NumberDecimal (decimal128) for money. Never floats.
- 3.The ledger is append-only; balance on the account is a cache you can always rebuild.
Want to experiment with these patterns? Open the playground and build the collections yourself, or practice related skills in the challenges.