Introduction
Change streams let you watch for changes in your database in real time. This helps you react quickly when data updates happen.
const changeStream = collection.watch(pipeline, options);const changeStream = collection.watch();const changeStream = collection.watch([{ $match: { operationType: 'insert' }}]);
const changeStream = collection.watch([], { fullDocument: 'updateLookup' });
const { MongoClient } = require('mongodb'); async function watchInserts() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('shop'); const collection = db.collection('orders'); const changeStream = collection.watch([{ $match: { operationType: 'insert' } }]); console.log('Watching for new orders...'); changeStream.on('change', (change) => { console.log('New order inserted:', change.fullDocument); }); } watchInserts();
orders in MongoDB?watch().db.orders.watch() starts watching changes on the orders collection.products collection?
const changeStream = db.products.watch();
changeStream.on('change', (change) => {
console.log(change.operationType);
});products collection and logs the operationType.operationType is "insert".users collection but it throws an error:const changeStream = db.users.watch({ fullDocument: 'updateLookup' });
changeStream.on('change', (change) => {
console.log(change.fullDocument);
});watch optionswatch method accepts an optional aggregation pipeline array as the first argument, and options as the second argument.{ fullDocument: 'updateLookup' } directly as the first argument is incorrect; it should be the second argument after the pipeline array.fullDocument option should be passed as the second argument to watch() after the pipeline array -> Option Aorders collection. Which approach using change streams is best to minimize data transfer and improve performance?insert and update operations and projecting only necessary fields reduces data sent and improves performance.Pass the test and this pattern moves unknown