ChangeStream
首先,你需要连接到 mongodb 并获取一个指向数据库的指针:
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
db := client.Database("mydb")
db.Collection.WatchChangeStream
pipeline := mongo.Pipeline{
{{"$match", bson.D{{"operationType", "insert"}}}},
}
cursor, err := db.Collection("mycoll").Watch(context.TODO(), pipeline)
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.TODO())
for cursor.Next(context.TODO()) {
// 这里是循环体,每次插入都会执行一次
var event bson.M
if err := cursor.Decode(&event); err != nil {
log.Fatal(err)
}
// 获取插入数据
insertedData := event["fullDocument"].(bson.M)
ownerID := insertedData["OwnerID"]
name := insertedData["name"]
quotaSize := insertedData["QuotaSize"]
}
event["fullDocument"]OwnerIDnameQuotaSize
注意:
mydbmycoll