Enable Replica Set

Changing streams require a replica set configuration

Initiate MongoDB with the -replSet option. mongod --replSet rs0

Connect to the MongoDB instance using the MongoDB shellInitiate the replica set by running: rs.initiate()

Use Change Streams

Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog.

Open a change stream on a collection, database, or the entire deployment using MongoDB drivers in your application code.In Node JS

  const MongoClient = require('mongodb').MongoClient;
  const uri = "your_mongodb_uri";
  const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

  async function monitorChanges() {
    try {
      await client.connect();
      const database = client.db("yourDatabase");
      const collection = database.collection("yourCollection");

      const changeStream = collection.watch();
      changeStream.on("change", (next) => {
        console.log(next);
        // handle change
      });
    } catch (e) {
      console.error(e);
    }
  }

  monitorChanges();

4. Implement Your Application Logic

Develop your application logic to react to the data changes captured by the change streams. This could involve updating user interfaces in real-time, triggering processes or alerts, or integrating with other systems.

https://www.mongodb.com/developer/products/mongodb/real-time-data-javascript/