AlgoViz

MongoDB

medium 34 min

MongoDB is a document database: it stores whole JSON-like records, keeps them on a replica set with one primary, and splits big collections over shards by a shard key.

See it run

Follow a write through a replica set, a failover, a routed query, a shard key, a pipeline, a transaction and a change stream.

Operations

Write with majority

The primary applies the write, a secondary copies it, and only then does the client hear success.

Step 1 of 5

The write arrives

Replica setwriteoplogoplogAppdriverPrimarycacheSecondary ASecondary B

The driver knows the members and sends the write to the primary.

Step 1: The write arrives

def write(doc, w="majority"):    primary.cache.apply(doc)    primary.journal.append(doc)    primary.oplog.append(doc)    acks = 1 + wait_for_secondaries()    need = len(members) // 2 + 1 if w == "majority" else w    return acks >= need
Waits for
One secondary
Protects from
Loss of the primary
w: 1
faster, may be rolled back

Majority has been the default since 5.0. Say what w: 1 would risk.

In the real world

The same mongodb doing real jobs. Pick one and step through it.

A page shows paid orders above 10 euros, newest first.

Step 1 of 3

No index

examinedreturnedplan
none2,000,00012COLLSCAN

Two million documents are read to return twelve.

Step 1: No index

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Sharding by time

    critical

    Each new value is the largest, so one shard takes every insert.

    Wrong
    sh.shardCollection("shop.orders", {"createdAt": 1})
    Right
    sh.shardCollection("shop.orders", {"customerId": 1, "createdAt": 1})
  • An array without an end

    critical

    The document gets slower with each element and stops at 16 MiB.

    Wrong
    posts.update_one(q, {"$push": {"comments": c}})
    Right
    comments.insert_one({"postId": post_id, "text": c})
  • Expecting your own write from a secondary

    major

    Secondaries lag. The user saves and sees the old value.

    Wrong
    db.with_options(read_preference=SECONDARY).users.find_one(q)
    Right
    db.users.find_one(q)   # primary, or a causal session
  • Filtering late in a pipeline

    major

    Grouping a million documents and then dropping most of them wastes memory and cannot use the index.

    Wrong
    [{"$group": g}, {"$match": {"_id": "books"}}]
    Right
    [{"$match": {"category": "books"}}, {"$group": g}]

Interview tips

  • How to explain it

    • One document for what is read together.
    • One primary, a majority to confirm and to elect.
    • One shard key that spreads writes and fits queries.
  • Memory trick

    • ESR: equality, sort, range.
    • Two of three, three of five.
    • Read together, store together.
  • Reach for it when

    • Records vary in shape.
    • Nested data is read whole.
    • The model changes often.
  • Look elsewhere when

    • Every request joins many kinds of record.
    • Most writes change several documents.
    • Only exact keys are read: a key-value store is simpler.