golang连接mongodb数据库

  1. 方法1

//-----------------c1.go-------------------

package conf

import (
    "gopkg.in/mgo.v2"
    "fmt"
)

func Ccdb2() (*mgo.Database, *mgo.Session)  {

    mgo_url := "mongodb://t1:t1@localhost:27017/test?authMechanism=SCRAM-SHA-1"

    session, err := mgo.Dial(mgo_url)

    session.SetMode(mgo.Monotonic, true)

    db := session.DB("test") //数据库名称
    
    if err != nil {
        fmt.Println("------连接数据库失败------------")
        panic(err)
    }
    fmt.Println("------ConnectionDb-----2-------")
    return db, session
}
func ColoseDb() {
    _, session := ConnectionDb()
    defer session.Close()
}
func PersonDocument() *mgo.Collection {
    db, _ := Ccdb2()
    conn := db.C("person")
    return conn
}


//-----------------c2.go-------------------


//查询出一个集合
func GetPeople(w http.ResponseWriter, req *http.Request) {
    fmt.Println("\n------------查询出一个集合--------------")

    var person []documents.Person
    
    //conf.PersonDocument().Find(bson.M{"name": "aa"}).All(&person)
    conf.PersonDocument().Find(nil).All(&person)

    for _, value := range person {
        fmt.Println(value.Name)
    }
    conf.ColoseDb()//关闭数据库

    json.NewEncoder(w).Encode(person)
}
  1. 方法2

//-----------------c1.go-------------------

package conf

import (
    "gopkg.in/mgo.v2"
    "fmt"
)

func Ccdb2() (*mgo.Database, *mgo.Session)  {

    mgo_url := "mongodb://t1:t1@localhost:27017/test" // 可以代替下面两步


    session, err := mgo.Dial(mgo_url)

    session.SetMode(mgo.Monotonic, true)

    db := session.DB("test") //数据库名称
    
    if err != nil {
        fmt.Println("------连接数据库失败------------")
        panic(err)
    }
    fmt.Println("------ConnectionDb-----2-------")
    return db, session
}
func ColoseDb() {
    _, session := ConnectionDb()
    defer session.Close()
}
func PersonDocument() *mgo.Collection {
    db, _ := Ccdb2()
    conn := db.C("person")
    return conn
}

//-----------------c2.go-------------------


//查询出一个集合
func GetPeople(w http.ResponseWriter, req *http.Request) {
    fmt.Println("\n------------查询出一个集合--------------")

    var person []documents.Person
    
    //conf.PersonDocument().Find(bson.M{"name": "aa"}).All(&person)
    conf.PersonDocument().Find(nil).All(&person)

    for _, value := range person {
        fmt.Println(value.Name)
    }
    conf.ColoseDb()//关闭数据库

    json.NewEncoder(w).Encode(person)
}
  1. 方法3

//-----------------c1.go-------------------

package conf

import (
    "gopkg.in/mgo.v2"
    "fmt"
)

func Ccdb2() (*mgo.Database, *mgo.Session)  {

    mgo_url := "localhost:27017"//登录地址 第一步

    session, err := mgo.Dial(mgo_url)

    session.SetMode(mgo.Monotonic, true)

    err = session.DB("test").Login("t1", "t1")//登录 认证 第二步
    if err != nil {
        panic(err)
    }

    db := session.DB("test") //数据库名称
    
    if err != nil {
        fmt.Println("------连接数据库失败------------")
        panic(err)
    }
    fmt.Println("------ConnectionDb-----2-------")
    return db, session
}
func ColoseDb() {
    _, session := ConnectionDb()
    defer session.Close()
}
func PersonDocument() *mgo.Collection {
    db, _ := Ccdb2()
    conn := db.C("person")
    return conn
}

//-----------------c2.go-------------------


//查询出一个集合
func GetPeople(w http.ResponseWriter, req *http.Request) {
    fmt.Println("\n------------查询出一个集合--------------")

    var person []documents.Person
    
    //conf.PersonDocument().Find(bson.M{"name": "aa"}).All(&person)
    conf.PersonDocument().Find(nil).All(&person)

    for _, value := range person {
        fmt.Println(value.Name)
    }
    conf.ColoseDb()//关闭数据库

    json.NewEncoder(w).Encode(person)
}
  1. 方法4
//-----------------c1.go-------------------

func PersonDocument() *mgo.Collection {
    dail_info := &mgo.DialInfo{
        Addrs:  []string{"127.0.0.1"},
        Direct: false,
        Timeout: time.Second * 1,
        Database: "test",
        Source: "test",
        Username: "t1",
        Password: "t1",
        PoolLimit: 1024,
    }

    session, err := mgo.DialWithInfo(dail_info)
    if err != nil {
        fmt.Printf("mgo dail error[%s]\n", err.Error())

    }

    defer session.Close()

    // set mode
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("test").C("person")
    return c
}


//-----------------c2.go-------------------


//查询出一个集合
func GetPeople(w http.ResponseWriter, req *http.Request) {
    fmt.Println("\n------------查询出一个集合--------------")

    var person []documents.Person
    
    //conf.PersonDocument().Find(bson.M{"name": "aa"}).All(&person)
    conf.PersonDocument().Find(nil).All(&person)

    for _, value := range person {
        fmt.Println(value.Name)
    }
    conf.ColoseDb()//关闭数据库

    json.NewEncoder(w).Encode(person)
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • [{"reportDate": "2018-01-23 23:28:49","fluctuateCause": n...
    加勒比海带_4bbc阅读 898评论 1 2
  • 【1】7,9,-1,5,( ) A、4;B、2;C、-1;D、-3 分析:选D,7+9=16;9+(-1)=8;(...
    Alex_bingo阅读 19,857评论 1 19
  • 1.埋点是做什么的 2.如何进行埋点 3.埋点方案的设计 近期常被问到这个问题,我担心我的答案会将一些天真烂漫的孩...
    lxg阅读 2,364评论 0 1
  • 1.角点检测简述 角点检测是计算机视觉系统中用来提取图像特征的一种方法,又称为特征点检测.广泛用于运动检测,图像匹...
    Pello_Luo阅读 2,953评论 0 0
  • 我静静地伫立在窗台 发现自己早已经不在 托腮凝思了 邻居的妹妹 走了 无邪的孩童 长大了 爽朗的笑声 消失了 只是...
    江舟泊客阅读 898评论 3 3

友情链接更多精彩内容