Go·使用mongoDB及安装mgo

Go·使用mongoDB及安装mgo

其中 mongoDB 不适合大型项目,目前主流应用的大型数据库产品有Oracle、IBM DB2、微软SQL Server、MYSQL和Sybase等。

golang使用mongoDB需要先安装 bzr 工具

1】终端安装 bzr

brew install bzr
//或者
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

2】终端修改环境

go env -w GO111MODULE=auto

3】终端安装 mgo

go get gopkg.in/mgo.v2

4】使用mgo 引入包名

import

 (

    "gopkg.in/mgo.v2"

    "gopkg.in/mgo.v2/bson"

)

5】链接有账号的数据库

package main

//golang对 MongoDB数据库操作
// 终端运行 go env -w GO111MODULE=auto
// 终端运行 go get gopkg.in/mgo.v2

import (
    "fmt"
    "os"

    "gopkg.in/mgo.v2"
)

func main() {
    session := InitMongoSession("abcd") //链接名称为livingwall数据库

    myDB := session.DB("abcd")
    collects, err := myDB.CollectionNames()
    if err != nil {
        fmt.Println("CollectionNames-error:", err)
        os.Exit(0)
    }
    fmt.Println(collects)

}

//链接数据库
func InitMongoSession(DB string) *mgo.Session {
    mHost := "127.0.0.1" //数据库ip地址
    mPort := "27017"          //端口号
    //mDBName := myDB  //你要连接的表,也可以后面再选,都行
    mUsername := "abc" //mongodb的账号
    mPassword := "abc" //mongodb的密码
    session, err := mgo.Dial(mHost + ":" + mPort)
    if err != nil {
        fmt.Println("mgo.Dial-error:", err)
        os.Exit(0)
    }
    session.SetMode(mgo.Eventual, true)

    myDB := session.DB(DB) //选择 "livingwall" 数据库
    //出现server returned error on SASL authentication step: Authentication failed. 这个错也是因为没有在livingwall数据库下登录
    err = myDB.Login(mUsername, mPassword) //登陆数据库
    if err != nil {
        fmt.Println("Login-error:", err)
        os.Exit(0)
    }
    //myDB = session.DB(Livingwall) //如果要在这里就选择数据库,这个myDB可以定义为全局变量
    session.SetPoolLimit(10) //设置池限制
    return session
}
513 Views
分享你的喜爱
linwute
linwute

我要像梦一样自由,像大地一样宽容;
在艰辛放逐的路上,点亮生命的光芒;
我要像梦一样自由,像天空一样坚强;
在曲折蜿蜒的路上,体验生命的意义;

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注