流行的mgo
司机 (github.com/go-mgo/mgo https://github.com/go-mgo/mgo)由古斯塔沃·尼迈耶(Gustavo Niemeyer)开发的已停止使用(无人维护)。而且它不支持变更流。
社区支持分叉github.com/globalsign/mgo https://github.com/globalsign/mgo状况要好得多,并且已经添加了对变更流的支持(请参阅详细信息在这里 https://github.com/globalsign/mgo/pull/97).
要观察集合的变化,只需使用Collection.Watch() https://godoc.org/github.com/globalsign/mgo#Collection.Watch返回值的方法mgo.ChangeStream https://godoc.org/github.com/globalsign/mgo#ChangeStream。这是一个使用它的简单示例:
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
}
另请注意,有一个officialMongoDB Go 驱动程序正在开发中,在这里宣布:考虑引入官方 MongoDB Go 驱动程序对社区的影响 https://engineering.mongodb.com/post/considering-the-community-effects-of-introducing-an-official-golang-mongodb-driver
目前它处于α (!!)阶段,所以要考虑到这一点。它可以在这里找到:github.com/mongodb/mongo-go-driver https://github.com/mongodb/mongo-go-driver。它还已经支持变更流,类似地通过Collection.Watch() https://godoc.org/github.com/mongodb/mongo-go-driver/mongo#Collection.Watch方法(这是一个不同的mongo.Collection
类型,与mgo.Collection
)。它返回一个mongo.Cursor https://godoc.org/github.com/mongodb/mongo-go-driver/mongo#Cursor你可以这样使用:
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)
}