Lesson 4: The MongoDB Operation Log / Learn

Code Summary: The MongoDB Operation Log

Review the following code, which demonstrates how to access and retrieve the status of the oplog.

Retrieve the Most Recent Entries in the oplog

The following code shows how to retrieve the most recent entries in the oplog. First, insert multiple documents into the sample_supplies database to populate the oplog collection with data. To do so, use the following code:

use sample_supplies

db.sales.updateMany({}, {$inc: {"customer.satisfaction": 1}});

Then switch to the local database and examine its collections by using the following commands:

use local

show collections

Next, use the find() command on the oplog.rs collection. Query the namespace field, which is abbreviated with "ns", followed by the name of the desired database and collection, by using dot notation.

Then, sort by the natural descending order by using the $natural operator followed by -1. Finally, limit the results to 5 by using limit() followed by 5. Here’s an example:

db.oplog.rs.find({"ns" : "sample_supplies.sales"}).sort({$natural: -1}).limit(5)

Retrieve Information About the oplog

Use the rs.printReplicationInfo() command to retrieve information about the oplog, including its size and certain events. Here’s an example:

rs.printReplicationInfo()

Retrieve Information About the Secondaries’ oplog

Use the rs.printSecondaryReplicationInfo() command to retrieve information about the secondaries’ oplog:

rs.printSecondaryReplicationInfo()