0
0
MongoDBquery~5 mins

Oplog and replication mechanism in MongoDB

Choose your learning style9 modes available
Introduction

The oplog helps keep copies of data in sync across multiple MongoDB servers. It records changes so all copies stay updated.

You want to keep a backup server updated automatically.
You need to share data across different locations for faster access.
You want to avoid losing data if one server fails.
You want to scale reads by having multiple copies of data.
You want to track changes made to your database over time.
Syntax
MongoDB
No direct query syntax; oplog is a special collection named 'oplog.rs' in the local database used internally by MongoDB replication.
The oplog is a capped collection that stores a rolling log of all operations that modify the data.
Replication uses the oplog to copy changes from the primary server to secondary servers.
Examples
This command shows the last 5 operations recorded in the oplog.
MongoDB
use local
 db.getCollection('oplog.rs').find().limit(5).sort({$natural:-1})
Shows the status of the replica set, including which server is primary and which are secondaries.
MongoDB
rs.status()
Starts a new replica set to enable replication.
MongoDB
rs.initiate()
Sample Program

This sequence starts a replica set, checks its status, and shows the last 3 operations in the oplog.

MongoDB
rs.initiate()
rs.status()
use local
db.getCollection('oplog.rs').find().limit(3).sort({$natural:-1})
OutputSuccess
Important Notes

The oplog is only accessible on replica set members, not standalone servers.

Oplog entries include the operation type: insert (i), update (u), delete (d), etc.

Replication ensures data is copied from the primary to secondaries by replaying oplog entries.

Summary

The oplog is a special log that records all data changes in MongoDB replica sets.

Replication uses the oplog to keep multiple servers' data in sync automatically.

This helps with data safety, scaling, and availability.