Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to Listen for Changes to a MongoDB Collection?
Next article icon

How to Listen for Changes to a MongoDB Collection?

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Tracking changes in MongoDB is essential for applications requiring real-time updates or synchronization with the database. Traditionally, this was achieved through polling, which could be inefficient. MongoDB offers more effective methods to track changes including Change Streams, the watch() method and Oplog Tailing.

In this article, We will learn about How to Track Changes in MongoDB by understanding various methods along with the practical implementation and so on.

How to Track Changes in MongoDB?

In many applications, it's crucial to provide users with real-time updates based on changes in the database. Traditionally, this was done by regularly checking (polling) the database for changes which could be inefficient and put unnecessary strain on the database server.

MongoDB offers some methods that help us to listen for changes to a MongoDB collection as follows:

  1. Using Change Streams
  2. Using watch() Method
  3. Using Oplog Tailing

1. Change Streams

Change Streams were introduced in MongoDB 3.6 to provide a streamlined way to track changes in a MongoDB collection. They allow applications to subscribe to a continuous stream of data change events, providing a real-time data feed of changes happening in the database.

How to Use Change Streams:

  • Create a Change Stream: Use the watch() method to create a change stream on a collection.
  • Subscribe to Events: Listen for events such as 'insert', 'update', 'replace', 'delete', and 'invalidate'.
  • React to Changes: Handle change events and update the application state or trigger appropriate actions.

Example:

// Get a reference to the 'myCollection' collection
const collection = db.collection('myCollection');

// Create a change stream on the collection
const changeStream = collection.watch();

// Set up an event listener for the 'change' event
changeStream.on('change', (change) => {
// Log the change event to the console
console.log('Change event:', change);

// React to the change event here
// This is where you would update your application state
// or trigger other actions based on the database change
});

Explanation:

The code snippet sets up a real-time listener on a MongoDB collection named 'myCollection'. It uses the watch() method to create a change stream, allowing the application to be notified of any changes (like inserts, updates, or deletes) happening in this collection. When a change occurs, it triggers the 'change' event, executing a callback function that logs the details of the change event. This mechanism is used to perform real-time reactions to database changes within an application.

2. The 'watch()' Method

The 'watch()' method in MongoDB allows applications to open a change stream against a collection, providing real-time notifications of data changes.

This method is particularly useful for applications that need to trigger actions or notifications in response to database updates.

Syntax:

const changeStream = collection.watch([pipeline], [options]);

Explanation:

  • collection: The MongoDB collection to watch.
  • pipeline: An optional array of aggregation pipeline stages to filter or transform the change events.
  • options: Optional settings for the change stream.

Example:

Consider a messages collection in a chat application. To listen for new messages, you can use the watch() method as follows:

// Import the MongoClient class from the MongoDB driver
const MongoClient = require('mongodb').MongoClient;

// Specify the MongoDB connection URI (replace 'your_mongodb_uri' with your actual URI)
const uri = "your_mongodb_uri";

// Create a new MongoClient instance with connection options
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

// Connect to the MongoDB server
client.connect(err => {
// Access the 'messages' collection in the 'chat' database
const collection = client.db("chat").collection("messages");

// Open a change stream on the 'messages' collection
const changeStream = collection.watch();

// Listen for 'change' events from the change stream
changeStream.on("change", next => {
// Log the details of the change event
console.log("New change:", next);
});
});

Output:

When a new message is added to the 'messages' collection, the change stream triggers the "change" event, logging something like:

New change: {
"_id": "...",
"operationType": "insert",
"fullDocument": {
"_id": "...",
"text": "Hello, World!",
"sender": "John Doe",
"timestamp": "2021-01-01T00:00:00Z"
},
"ns": {
"db": "chat",
"coll": "messages"
},
"documentKey": {
"_id": "..."
}
}

Explanation: This output shows the details of the change, including the operation type '(insert)' and the new message data under 'fullDocument'.

3. Oplog Tailing

MongoDB's oplog (operations log) is a capped collection that records all write operations that modify data in a MongoDB database.

Oplog tailing involves continuously querying the oplog to identify changes and react accordingly.

How to Use Oplog Tailing:

  • Connect to the Oplog: Access the oplog collection from the local database.
  • Query for Changes: Continuously monitor the oplog for new entries and process them.
  • React to Changes: Handle oplog entries and apply appropriate actions based on the type of operation.

Example:

// Get a reference to the oplog collection in the local database
const oplog = db.collection('oplog.rs').find({}).sort({ $natural: -1 }).limit(1);

// Set up a change event listener on the oplog collection
oplog.on('change', (change) => {
// Log the oplog entry to the console
console.log('Oplog entry:', change);
// React to oplog changes here
});

Explanation: In this code, we first obtain a reference to the oplog collection (oplog.rs) in the local database. We then use the find() method to retrieve the most recent entry in the oplog, sorting in reverse natural order ($natural: -1) and limiting the result to 1 entry. Finally, we set up a change event listener on the oplog collection, which will log the change to the console and allow for further reactions to oplog changes.

Conclusion

Overall, MongoDB provides several methods for tracking changes in a collection, each with its own advantages and use cases. Whether you choose to use Change Streams, the 'watch()' method, or oplog tailing depends on the specific requirements of our application. By utilizing these methods, you can create more responsive and efficient applications that can react in real-time to changes happening in the database.


Next Article
How to Listen for Changes to a MongoDB Collection?

P

poojashu00qn
Improve
Article Tags :
  • MongoDB
  • Databases
  • MongoDB Query

Similar Reads

    How to Add a Column in MongoDB Collection?
    In MongoDB, the ability to add new fields to collections without restructuring the entire schema is a powerful feature. Whether we are adapting to changing requirements or enhancing existing data, MongoDB offers several methods through easily we can easily add new fields to our collections. In this
    4 min read
    How to Copy a Collection From One Database to Another in MongoDB?
    Effective data management is crucial for MongoDB-dependent applications. As databases grow, the need to transfer collections between databases arises. This can be for creating development or testing environments, migrating data, or archiving historical information. MongoDB provides built-in capabili
    6 min read
    How to Changing the Primary Key in MongoDB Collection
    In MongoDB, the primary key uniquely identifies each document within a collection. While MongoDB automatically assigns a primary key using the _id field, there may be scenarios where we need to change the primary key to a different field or value. In this article, we'll explore how to change the pri
    5 min read
    How to List All Collections in the MongoDB Shell?
    Managing collections is a fundamental task in MongoDB database administration. Knowing how to list all collections in the MongoDB shell is essential for understanding your database structure and managing your data effectively. In this article, we'll explore how to list all collections in the MongoDB
    3 min read
    How to use TTL collections in MongoDB?
    TTL (Time-To-Live) collections in MongoDB is a special collection where it allows automatic deletion of documents after a specified duration. This technique is used in managing temporary data, such as user sessions cache logsHow TTL WorksTTL Index: You create a TTL index on a date field in your coll
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences