在 Golang 中,你可以使用 MongoDB 的 official Go driver 来监听 changestream,并获取变动前的字段值。下面是一个简单的示例代码:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
collection := client.Database("your_database").Collection("your_collection")
changeStreamOptions := options.ChangeStream().
SetFullDocument(options.UpdateLookup).
SetMaxAwaitTime(2 * time.Second) // 设置最大等待时间
pipeline := mongo.Pipeline{
bson.D{{"$match", bson.D{{"operationType", "update"}}}}, // 匹配更新操作
bson.D{{"$match", bson.D{{"updateDescription.updatedFields.A", bson.D{{"$exists", true}}}}}}, // 匹配包含A字段的更新
}
cursor, err := collection.Watch(ctx, pipeline, changeStreamOptions)
if err != nil {
log.Fatal(err)
}
for cursor.Next(ctx) {
var changeDoc struct{
FullDocument map[string]interface{} `bson:"fullDocument"`
UpdateDescription struct{
UpdatedFields map[string]interface{} `bson:"updatedFields"`
} `bson:"updateDescription"`
}
if err = cursor.Decode(&changeDoc); err != nil {
log.Fatal(err)
}
// 获取变动前的字段值
if value, ok := changeDoc.UpdateDescription.UpdatedFields["A"]; ok {
fmt.Println("变动前的值: ", value)
} else {
fmt.Println("未找到变动前的值")
}
// 处理其他操作...
}
}
这段代码使用 MongoDB 的 Go 驱动来创建一个 changestream,并设置了一些选项,例如最大等待时间和过滤条件。当监听到更新操作并匹配到 A 字段时,将输出变动前的字段值。
请注意,需要替换 mongodb://localhost:27017 为你实际的 MongoDB 连接字符串,并修改数据库名和集合名以适应你的环境。同时还需确保已安装正确版本的 MongoDB Go driver。
内容由零声教学AI助手提供,问题来源于学员提问




