要监听 MongoDB 的集合并提取指定字段,你可以使用 MongoDB 的 Change Streams 功能和 Golang 的官方驱动程序(mongo-go-driver)来实现。下面是一个示例代码:
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MyDocument struct {
ID string `bson:"_id"`
Field1 string `bson:"field1"`
Field2 string `bson:"field2"`
}
func main() {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
fmt.Println("Failed to create MongoDB client:", err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
fmt.Println("Failed to connect to MongoDB:", err)
return
}
collection := client.Database("your_database").Collection("your_collection")
pipeline := mongo.Pipeline{
// 只监听具有 field1 字段变化的操作
bson.D{{"$match", bson.D{{"updateDescription.updatedFields.field1", bson.M{"$exists": true}}}}},
}
changeStreamOpts := options.ChangeStream().
SetFullDocument(options.UpdateLookup).
SetMaxAwaitTime(5 * time.Second)
changeStream, err := collection.Watch(ctx, pipeline, changeStreamOpts)
if err != nil {
fmt.Println("Failed to create change stream:", err)
return
}
defer func() {
changeStream.Close(ctx)
client.Disconnect(ctx)
}()
for changeStream.Next(ctx) {
var changeDocument struct {
OperationType string `bson:"operationType"`
FullDocument MyDocument `bson:"fullDocument"`
}
if err := changeStream.Decode(&changeDocument); err != nil {
fmt.Println("Failed to decode change document:", err)
continue
}
fmt.Printf("Operation Type: %s\n", changeDocument.OperationType)
fmt.Printf("Field1 Value: %s\n", changeDocument.FullDocument.Field1)
}
if err := changeStream.Err(); err != nil {
fmt.Println("Change stream error:", err)
}
}
你需要将代码中的 mongodb://localhost:27017 替换为你实际的 MongoDB 连接字符串,以及 "your_database" 和 "your_collection" 分别替换为你要监听的数据库和集合名称。在 pipeline 中,我们使用 $match 阶段过滤出只有 “field1” 字段变化的操作。在每个变化事件上,我们提取了完整的文档信息,并输出了 “field1” 字段的值。
请确保已经安装了 Golang 的官方驱动程序(mongo-go-driver),你可以通过以下命令安装:
go get go.mongodb.org/mongo-driver/mongo
希望对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问




