rmdir.cn

db.collection.watch()

监听数据变更 (Change Streams)

语法

db.collection.watch(<pipeline>, <options>)

说明

Change Streams 允许应用程序实时监听集合、数据库或整个部署的数据变更事件(insert、update、delete、replace 等)。适用于实时通知、数据同步、审计日志等场景。需要副本集或分片集群。

参数

  • pipeline

    聚合管道,过滤感兴趣的变更事件

  • fullDocument

    "updateLookup" 返回更新后的完整文档

  • resumeAfter

    从指定断点恢复监听

  • startAtOperationTime

    从指定时间点开始监听

示例

监听集合变更

监听 users 集合的所有变更

const cursor = db.users.watch() while (!cursor.isExhausted()) { if (cursor.hasNext()) printjson(cursor.next()) }

仅监听 insert 事件

过滤只关注新增操作

db.orders.watch([{ $match: { operationType: "insert" } }])

获取更新后完整文档

update 事件返回更新后的文档

db.users.watch([], { fullDocument: "updateLookup" })