ZBLOG

golang 监听mongodb的集合,只监听指定字段后提取该指定字段

要监听 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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16990

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?