MongoDB 触发器,监听库/表变更记录
2020-09-25 本文已影响0人
LCSan
MongoDB 3.6版本之后支持Change Stream,,当MongoDB开启集群(副本集)时可以启用。此文记录Win10本地单进程MongoDB,监听指定表数据变更学习。
system: win10
MongoDB: v4.4.1
nodejs: v12.18.3.
python: v3.7.2
MongoDB副本集启动项
mongod.exe --dbpath ../data --replSet re0 --port 27020
MongoDB设置副本集
mongo.exe --port 27020
rs.initiate({ _id: "re0", members: [{_id:0,host:"127.0.0.1:27020"}]})
rs.status()
当控制台状态变为PRIMARY说明成功。
image.png
python版监听
# coding=utf-8
'''
Created on 2020年9月25日
@author: 瞌睡蟲子
'''
import pymongo
mongo_client = pymongo.MongoClient('127.0.0.1', 27020)
db = mongo_client['testDb']
col = db['testconn']
try:
# with col.watch() as stream:
with mongo_client.watch() as stream:
for insert_change in stream:
print(insert_change)
except pymongo.errors.PyMongoError as e:
print(e)
nodejs版监听
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://127.0.0.1:27020";
const dbName = "testDb"
const tableName = "testconn"
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect().then(db => {
//const changeStream = client.db(dbName).collection(tableName).watch();
const changeStream = client.watch();
changeStream.on("change", next => {
console.log(next);
});
});
重点
- 支持client,database,collection上都可以进行监听
with mongo_client.watch() as stream:
with db.watch() as stream:
with col.watch() as stream:
const changeStream = client.watch();
const changeStream = client.db(dbName).watch();
const changeStream = client.db(dbName).collection(tableName).watch();
- watch内部过滤
watch([{ '$match': { 'operationType': { $in: ['insert', 'update'] }, "ns.db": "testDb", "ns.coll": "conn" } }]);
过滤结构匹配:testDb库,conn表,的insert或update操作。
参考:
https://www.mongodb.com/blog/post/five-minute-mongodb--change-streams-and-mongodb-4x
https://zhuanlan.zhihu.com/p/69610164