$ ChangeStream - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$ ChangeStream

Tidak didukung oleh cluster elastis.

Tahap $changeStream agregasi membuka kursor aliran perubahan untuk memantau perubahan real-time ke koleksi. Ia mengembalikan perubahan dokumen peristiwa ketika menyisipkan, memperbarui, mengganti, atau menghapus operasi terjadi.

Parameter

  • fullDocument: Menentukan apakah akan mengembalikan dokumen lengkap untuk operasi update. Pilihannya adalah default atauupdateLookup.

  • resumeAfter: Opsional. Lanjutkan token untuk melanjutkan dari titik tertentu dalam aliran perubahan.

  • startAtOperationTime: Opsional. Stempel waktu untuk memulai aliran perubahan dari.

  • allChangesForCluster: Opsional. Nilai Boolean. Kapantrue, perhatikan semua perubahan di seluruh cluster (untuk database admin). Ketika false (default), hanya menonton koleksi yang ditentukan.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan menggunakan $changeStream panggung untuk memantau perubahan koleksi.

Contoh kueri

// Open change stream first const changeStream = db.inventory.aggregate([ { $changeStream: { fullDocument: "updateLookup" } } ]); // In another session, insert a document db.inventory.insertOne({ _id: 1, item: "Widget", qty: 10 }); // Back in the first session, read the change event if (changeStream.hasNext()) { print(tojson(changeStream.next())); }

Keluaran

{ _id: { _data: '...' }, operationType: 'insert', clusterTime: Timestamp(1, 1234567890), fullDocument: { _id: 1, item: 'Widget', qty: 10 }, ns: { db: 'test', coll: 'inventory' }, documentKey: { _id: 1 } }

Contoh kode

Untuk melihat contoh kode untuk menggunakan tahap $changeStream agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('inventory'); // Open change stream const changeStream = collection.watch([]); changeStream.on('change', (change) => { console.log('Change detected:', change); }); // Simulate insert in another operation setTimeout(async () => { await collection.insertOne({ _id: 1, item: 'Widget', qty: 10 }); }, 1000); // Keep connection open to receive changes // In production, handle cleanup appropriately } example();
Python
from pymongo import MongoClient import threading import time def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['inventory'] # Open change stream change_stream = collection.watch([]) # Insert document in separate thread after delay def insert_doc(): time.sleep(1) collection.insert_one({'_id': 1, 'item': 'Widget', 'qty': 10}) threading.Thread(target=insert_doc).start() # Watch for changes for change in change_stream: print('Change detected:', change) break # Exit after first change client.close() example()