Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to connect mongodb 3.0 in golang

Tags:

mongodb

go

mgo

When I upgrade my mongodb server to version 3.0 from 2.6 it can't connect from golang use mgo.

I add 'authMechanism=SCRAM-SHA-1' in connection string, and it still can't connect to the server. The error that I get is SASL support not enabled during build (-tags sasl)

like image 225
William Avatar asked Oct 19 '22 14:10

William


1 Answers

I had similar issue. Misleadingly I found around the network that has to be included the "labix.org/v2/mgo" package despite the fact that on the official site http://labix.org/mgo (at the time of the reading) it has newer and updated information that points to at least working for me package "gopkg.in/mgo.v2".

I hope this can help since I got to the same steps as you without success and then I have changed the package reference. This code worked in my case:

  package main

  import (
    "fmt"
    "time"

    "gopkg.in/mgo.v2"
  )

  //const MongoDb details
  const (
    hosts      = "ds026491.mongolab.com:26491"
    database   = "messagingdb"
    username   = "admin"
    password   = "youPassword"
    collection = "messages"
  )

  func main() {

    info := &mgo.DialInfo{
        Addrs:    []string{hosts},
        Timeout:  60 * time.Second,
        Database: database,
        Username: username,
        Password: password,
    }

    session, err1 := mgo.DialWithInfo(info)
    if err1 != nil {
        panic(err1)
    }

    col := session.DB(database).C(collection)

    count, err2 := col.Count()
    if err2 != nil {
        panic(err2)
    }
    fmt.Println(fmt.Sprintf("Messages count: %d", count))
  }

It is also on Github

like image 53
Velin Georgiev Avatar answered Nov 01 '22 07:11

Velin Georgiev