In MongoDB, the watch
operation is used to open a change stream on a collection. This method is essential for real-time monitoring of data changes in MongoDB collections.
db.collection.watch(pipeline, options)
The watch
method takes an optional pipeline
parameter to specify an aggregation pipeline for filtering the change events and an optional options
parameter to customize the change stream.
Let's look at some examples of how to use the watch
method in the programGuru
collection in MongoDB:
const changeStream = db.programGuru.watch();
changeStream.on('change', (change) => {
printjson(change);
});
This command opens a change stream on the programGuru
collection and prints each change event to the console.
const pipeline = [
{ $match: { 'fullDocument.age': { $gt: 30 } } }
];
const changeStream = db.programGuru.watch(pipeline);
changeStream.on('change', (change) => {
printjson(change);
});
This command opens a change stream on the programGuru
collection and prints change events where the age
field is greater than 30.
Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and opening a change stream to watch for changes.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
This step involves inserting documents into the programGuru
collection.
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
We insert multiple documents into the programGuru
collection.
This step involves using the watch
method to open a change stream on the programGuru
collection and monitor changes.
const changeStream = db.programGuru.watch();
changeStream.on('change', (change) => {
printjson(change);
});
We open a change stream on the programGuru
collection and print each change event to the console.
const pipeline = [
{ $match: { 'fullDocument.age': { $gt: 30 } } }
];
const changeStream = db.programGuru.watch(pipeline);
changeStream.on('change', (change) => {
printjson(change);
});
We open a change stream on the programGuru
collection and print change events where the age
field is greater than 30.
The MongoDB watch
operation is crucial for real-time monitoring of data changes in collections. Understanding how to use this method allows you to efficiently track and respond to changes within your MongoDB collections.