duanpuchen3142 2017-05-26 07:36
浏览 76
已采纳

是否可以使用mgo驱动程序运行mongo复制集命令?

Is it possible to run replica set commands like rs.initiate() and rs.add() using mgo driver from a golang application?

If yes, how??

  • 写回答

2条回答 默认 最新

  • dongtaihui5131 2017-06-03 09:20
    关注

    Thanks to @alex-blex's answer which gave me the start. But this is what finally worked for me:

    session, err := mgo.Dial("rs1.example.net?connect=direct")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    
    config := bson.M{
        "_id": "my_replica_set",
        "members": []bson.M{
            {"_id": 0, "host": "rs1.example.net:27017"},
            {"_id": 1, "host": "rs2.example.net:27017", "priority": 2},
            {"_id": 2, "host": "rs3.example.net", "arbiterOnly": true},
        },
    }
    result := bson.M{}
    if err := session.Run(bson.M{"replSetInitiate": config}, &result); err != nil {
        panic(err)
    }
    

    Notice the following:

    1. ?connect=direct in the connection string.

      If not specified, the connection will timeout, probably because the replica set has not been initialized yet.

    2. session.SetMode(mgo.Monotonic, true)

      Session mode should be monotonic as the default session used by mgo is primary which performs all operations on primary. Since the replica set has not been initialized yet, there wont be a primary and the operation (in this case, replSetInitiate) will just timeout

    3. "_id": "my_replica_set" in the config

      For this to work, the mongo servers will have to be started with the replica set name my_replica_set. One way of doing that would be:

      mongod --replSet my_replica_set
      
    4. As per Mgo docs use session.Run() for commands on the "admin" database
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格