注意MongoDB更改流 [英] Watch for MongoDB Change Streams

查看:154
本文介绍了注意MongoDB更改流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望我们的Go应用程序侦听集合中的数据更改.因此,在寻找解决方案的过程中,我们遇到了MongoDB的更改流.该链接还展示了针对多种语言(例如Python,Java,Nodejs等)的一些实现摘要.但是,Go并没有一段代码.

We want our Go application to listen to the data changes on a collection. So, googling in search for a solution, we came across MongoDB's Change Streams. That link also exhibits some implementation snippets for a bunch of languages such as Python, Java, Nodejs etc. Yet, there is no piece of code for Go.

我们使用 Mgo 作为驱动程序,但在更改流.

We are using Mgo as a driver but could not find explicit statements on change streams.

有人对使用Mgo或Go的任何其他Mongo驱动程序观看更改流有任何想法吗?

Does anyone have any idea on how to watch on Change Streams using that Mgo or any other Mongo driver for Go?

推荐答案

流行的mgo驱动程序( )已经变黑(未维护).而且它不支持变更流.

The popular mgo driver (github.com/go-mgo/mgo) developed by Gustavo Niemeyer has gone dark (unmaintained). And it has no support for change streams.

社区支持的叉子 github.com/globalsign/mgo 的状态要好得多,并且已经添加了对变更的支持流(请参见在此处详细说明).

要观看集合的更改,只需使用 Collection.Watch() 方法,该方法将为您返回 mgo.ChangeStream 的值.这是一个使用它的简单示例:

To watch changes of a collection, simply use the Collection.Watch() method which returns you a value of mgo.ChangeStream. Here's a simple example using it:

coll := ... // Obtain collection

pipeline := []bson.M{}

changeStream := coll.Watch(pipeline, mgo.ChangeStreamOptions{})
var changeDoc bson.M
for changeStream.Next(&changeDoc) {
    fmt.Printf("Change: %v\n", changeDoc)
}

if err := changeStream.Close(); err != nil {
    return err
}


还请注意,有一个官方 MongoDB Go驱动程序正在开发中,它在此处宣布:


Also note that there is an official MongoDB Go driver under development, it was announced here: Considering the Community Effects of Introducing an Official MongoDB Go Driver

当前处于<​​strong> alpha(!!)阶段,因此请考虑到这一点.它可以在这里找到: github.com/mongodb/mongo-go-driver .它也已经通过 Collection.Watch() 方法(这是另一种mongo.Collection类型,与mgo.Collection无关).它会返回一个 mongo.Cursor 这个:

It is currently in alpha (!!) phase, so take this into consideration. It is available here: github.com/mongodb/mongo-go-driver. It also already has support for change streams, similarly via the Collection.Watch() method (this is a different mongo.Collection type, it has nothing to do with mgo.Collection). It returns a mongo.Cursor which you may use like this:

var coll mongo.Collection = ... // Obtain collection

ctx := context.Background()

var pipeline interface{} // set up pipeline

cur, err := coll.Watch(ctx, pipeline)
if err != nil {
    // Handle err
    return
}
defer cur.Close(ctx)

for cur.Next(ctx) {
    elem := bson.NewDocument()
    if err := cur.Decode(elem); err != nil {
        log.Fatal(err)
    }

    // do something with elem....
}

if err := cur.Err(); err != nil {
    log.Fatal(err)
}

这篇关于注意MongoDB更改流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆