Introduction to MongoDB collection.watch() Method
The watch()
method in MongoDB can monitor data changes in a collection and return corresponding change streams. When data in a collection changes, the watch()
method will return the corresponding document or document changes, such as inserting, updating, or deleting documents.
Syntax
The syntax of the watch()
method is as follows:
db.collection.watch(pipeline, options)
Where pipeline
and options
are both optional parameters.
Use Cases
The watch()
method is useful for monitoring data changes in collections, especially when real-time data processing is required, such as data synchronization, real-time analysis, and so on.
Example
Here’s a complete example of using the watch()
method:
Create a connection
const MongoClient = require("mongodb").MongoClient
const uri = "mongodb://localhost:27017/test"
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
})
Connect to the database and create a collection
client.connect((err) => {
const collection = client.db("test").collection("users")
const changeStream = collection.watch()
changeStream.on("change", (next) => {
console.log(next)
})
collection.insertOne({ name: "Tom", age: 18 })
collection.updateOne({ name: "Tom" }, { $set: { age: 20 } })
collection.deleteOne({ name: "Tom" })
client.close()
})
In the above example, we first use MongoClient
to connect to the database and create a collection named users
. Then we call the watch()
method to monitor data changes in the collection and print the change stream to the console. Next, we insert, update, and delete some documents, which will trigger the watch()
method to return the corresponding change stream. Finally, we close the connection to the database.
Conclusion
The watch()
method in MongoDB is useful for monitoring data changes in collections, especially when real-time data processing is required. It can be used to listen to data change streams when developing real-time applications or performing data synchronization and real-time analysis.