次のことを行う必要があります:
-
operationType: 'insert'を指定します 。更新を監視したくないので、updateLookupは必要ありません。 。 - 適切な
集約パイプライン を作成します operationTypeを含むフィルター用 。 - 集約パイプラインは、
watch()によって返されるドキュメントをフィルタリングします 。出力例は、イベントの変更ページ> 。
watch() ChangeStreamを返します 。 closeを起動します 、change 、end 、およびerror イベント。 ChangeStream
を参照してください 詳細については。
これは、insertをリッスンするチェンジストリームの完全な例です。 データベースの操作test コレクションtest 。 {a: 1}フィールドを持つドキュメントを出力します ('fullDocument.a': 1 )、更新、aの他の値の挿入を無視します 、またはフィールドaのないもの 。
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://localhost:27017/test?replicaSet=replset'
const insert_pipeline = [
{$match: {operationType: 'insert', 'fullDocument.a': 1}}
]
function watch_insert(con, db, coll) {
console.log(new Date() + ' watching: ' + coll)
con.db(db).collection(coll).watch(insert_pipeline)
.on('change', data => {
console.log(data)
})
}
async function run() {
con = await MongoClient.connect(uri, {"useNewUrlParser": true})
watch_insert(con, 'test', 'test')
}
run()