Open-Source Wikis

/

MongoDB

/

Applications

/

mongod

mongodb/mongo

mongod

mongod is the MongoDB database server. A single mongod process hosts a set of databases, runs the storage engine, applies replication, and answers wire-protocol commands. In a production deployment, multiple mongod instances form a replica set, and many replica sets ("shards") form a cluster behind one or more mongos routers.

Purpose

A mongod process:

  • Listens on a TCP (and optionally TLS or gRPC) port for the wire protocol.
  • Authenticates clients (SCRAM, x.509, LDAP, Kerberos) and authorizes operations against role-based access control.
  • Parses each command into an IDL-typed request and dispatches to a Command.
  • Runs reads and writes through the shard role — including locking, transaction state, and shard versioning.
  • Writes durable changes via the storage engine (WiredTiger).
  • Records oplog entries for replication and downstream consumers (change streams, secondary appliers).
  • Runs background services: the TTL monitor, index builds, primary-only services, the replication coordinator, the global catalog DDL coordinators, the FTDC collector, and dozens more.

Entry point

graph TD
    Main[mongod_main.cpp<br/>::main]
    Init[initialize_server_global_state.cpp]
    SC[ServiceContext setup]
    Storage[Storage engine init<br/>StorageEngineInit]
    Repl[ReplicationCoordinator init]
    Listen[transport listener]

    Main --> Init
    Init --> SC
    SC --> Storage
    Storage --> Repl
    Repl --> Listen
    Listen -->|accept loop| Listen

The entry point is in src/mongo/db/mongod_main.cpp (mongod_main), wrapped by src/mongo/db/mongod.cpp for the platform-specific main. Startup proceeds through:

  1. Option parsing (src/mongo/db/mongod_options.cpp and the IDL files alongside it).
  2. Global state initialization (initialize_server_global_state.cpp) — log file, locale, signal handlers, ServiceContext.
  3. Storage engine startup — opens or creates the dbpath, recovers any incomplete writes, and rebuilds in-progress indexes.
  4. Replication coordinator startup (src/mongo/db/repl/) — joins the replica set, reads the local config, runs the election/initial-sync state machine.
  5. Sharding registration when the binary is part of a cluster — registers with the shard role catalog and config-server cache.
  6. Background services — TTL monitor, index-build coordinator, primary-only-service registry, periodic runners, FTDC.
  7. Listener accept loop in src/mongo/transport/. Each accepted session becomes a Session handed to the service entry point.

Service entry point

The dispatcher is src/mongo/db/service_entry_point_shard_role.cpp. For each OP_MSG:

sequenceDiagram
    participant Net as Transport
    participant SEP as ServiceEntryPointShardRole
    participant CmdReg as Command registry
    participant Cmd as Command::run
    participant Storage as ShardRole / Storage
    participant Repl as Replication / OpObserver

    Net->>SEP: handleRequest(opCtx, msg)
    SEP->>SEP: parse OpMsg, ApiParameters, OperationSession
    SEP->>SEP: auth, audit, OperationContext deadline
    SEP->>CmdReg: lookup command name
    CmdReg-->>SEP: Command*
    SEP->>Cmd: typedRun(parsedRequest)
    Cmd->>Storage: acquireCollection(...) + WUOW
    Storage-->>Cmd: snapshot / write target
    Cmd->>Repl: OpObserver hooks for writes
    Cmd-->>SEP: BSONObj reply
    SEP-->>Net: serialize OP_MSG reply

The dispatcher also handles:

  • API parameter checks (src/mongo/db/api_parameters.idl) — the user's declared API version.
  • Retryable writes / sessions — extracted from the request and used to look up the TransactionParticipant.
  • Read concern / write concern — parsed and applied via the read/write concern defaults system.
  • Error labels — attaches RetryableWriteError, TransientTransactionError, etc.

Background services

mongod runs a long list of background work, most of which is registered via the ServiceContext decoration system or as a Primary-Only Service:

Service Where Purpose
Replication coordinator src/mongo/db/repl/ Election, heartbeats, oplog application, initial sync.
Index build coordinator src/mongo/db/index_builds/ Coordinates two-phase index builds across replica-set members.
TTL monitor src/mongo/db/ttl/ Deletes expired documents.
OpObserver chain src/mongo/db/op_observer/ Writes oplog entries and notifies subscribers.
Primary-only services src/mongo/db/repl/primary_only_service* Stateful workers that only run on a primary.
Global catalog DDL coordinators src/mongo/db/global_catalog/ddl/ Drives sharded create, drop, rename, shardCollection, reshardCollection.
Sharding state machine src/mongo/db/s/ Migration source/destination state machines, range deleter, cluster parameter sync.
FTDC collector src/mongo/db/ftdc/ Periodic diagnostic snapshots.
Watchdog src/mongo/watchdog/ Detects stuck filesystems / data directories.
Process health src/mongo/db/process_health/ Tracks subsystem liveness and may abort if unhealthy.

Key source files

File Purpose
src/mongo/db/mongod_main.cpp Top-level startup and shutdown.
src/mongo/db/mongod_options.cpp CLI option parsing.
src/mongo/db/initialize_server_global_state.cpp Sets up signals, logging, and the ServiceContext.
src/mongo/db/service_entry_point_shard_role.cpp Top-level command dispatch.
src/mongo/db/commands.cpp The Command registry and validation hooks.
src/mongo/db/operation_context.cpp The OperationContext.
src/mongo/db/curop.cpp Per-operation diagnostic state used by db.currentOp().
src/mongo/db/op_observer/ Hooks fired on every write; appends to the oplog.
src/mongo/db/shard_role/ Modern acquireCollection API with shard versioning.
src/mongo/db/storage/storage_engine.h The StorageEngine abstraction.
src/mongo/db/storage/wiredtiger/ The WiredTiger wrapper.

Integration points

mongod integrates with:

  • Drivers via the transport layer and the wire protocol.
  • mongos and other mongods via the same wire protocol used for inter-node communication (replication heartbeats, sharding migrations, transaction coordination).
  • Config server when part of a sharded cluster — for catalog updates and cluster parameter propagation.
  • Operating system through the storage engine (file I/O, fsync, mmap, direct I/O), the watchdog (filesystem heartbeats), and the kernel TLS/socket layers.

Entry points for modification

Adding a command means writing an IDL file, a Command subclass, and a BUILD.bazel entry in src/mongo/db/commands/. Wiring up new background work is usually a PrimaryOnlyService if it's primary-only, a ServiceContext decoration plus a ReplicaSetAwareService if it needs to react to replication state, or a PeriodicRunner for simple periodic tasks. Touching the request lifecycle starts at service_entry_point_shard_role.cpp; touching durability or the oplog goes through the op observer and replication.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

mongod – MongoDB wiki | Factory