I'm newbie for MongoDB and I’ve tried to use collection.Watch() from "go.mongodb.org/mongo-driver/mongo" lib. and code from https://github.com/minhthuy30197/change_stream/blob/master/main.go. Then I build and run it stop immediately.
I’ve tried to run again and again and it also stop running. I’ve switch using between go run main.go
and ./testStreams
and it still stop running
So this is my edited code.
clientOptions := options.Client().
ApplyURI("mongodb://localhost:27017/test")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatalf("Failed to create the new client: %v", err)
}
ctx := context.Background()
if err := client.Connect(ctx); err != nil {
log.Printf("Failed to open client connection: %v", err)
}
defer client.Disconnect(ctx)
coll := client.Database("test").Collection("streams")
var pipeline interface{}
for {
cur, err := coll.Watch(ctx, pipeline)
if err != nil {
log.Fatalf("Watch error: %v", err)
}
defer cur.Close(ctx)
log.Println(cur)
for cur.Next(ctx) {
elem := CSElem{}
if err := cur.Decode(elem); err != nil {
log.Fatalf("Decode error: %v", err)
}
log.Println(elem)
}
if err := cur.Err(); err != nil {
log.Fatalf("Error detected: %v", err)
}
}
When I edit then error appear
2019/08/07 13:46:39 Failed to open client connection: topology is connected or connecting exit status 1
How should I fix??