dongran1779 2019-08-05 03:33
浏览 499

MongoDB collection.Watch()编译并停止运行

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??

  • 写回答

1条回答 默认 最新

  • dongliang1654 2019-08-27 02:09
    关注

    As mentioned on the comment, utilising mongo-go-driver v1+ a new client instance need to be created first before making a connection. For example:

    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/test")
    client, err := mongo.NewClient(clientOptions)
    if err != nil {log.Fatal(err)}
    
    // Timed out after 10 seconds of trying to connect 
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    
    err = client.Connect(ctx)
    if err != nil { log.Fatal(err)}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line