天天看點

Golang使用MongoDB

go使用mongo

文檔連結:https://godoc.org/labix.org/v2/mgo

mongo包下載下傳:go get github.com/go-mgo/mgo

import (
	"fmt"
	"gopkg.in/mgo.v2"
	_ "gopkg.in/mgo.v2/bson"
	"os"
)

var Session *mgo.Session
var Databases *mgo.Database
var MgoError error

const (
	MONGO_HOST	= ""
	MONGO_PORT	= ""
	MONGO_DB	= ""
	MONGO_USER	= ""
	MONGO_PWD	= ""
)

func init() {
	// 建立連結
	Session, MgoError = mgo.Dial(fmt.Sprintf("%s:%s", MONGO_HOST, MONGO_PORT))
	if MgoError != nil {
		fmt.Println("連結失敗!")
		os.Exit(1)
	}
	// 選擇DB
	Databases = Session.DB(MONGO_DB)
	// 登陸
	MgoError = Databases.Login(MONGO_USER, MONGO_PWD)
	if MgoError != nil {
		fmt.Println("登陸驗證失敗!")
		os.Exit(1)
	}
	// defer Session.Close()
}

func Demos() {
	// 選擇一個要操作的Collection
	c := Databases.C("demo")
	// count
	fmt.Println(c.Count())
	// insert
	c.Insert(map[string]string{"name": "馬超"})
	// update
	c.Update(map[string]string{"name": "馬超"}, map[string]string{"name": "黃忠"})
	// remove
	c.Remove(map[string]string{"name": "馬超"})
	// find - count
	num, MgoError := c.Find(map[string]string{"name": "黃忠"}).Count()
	if MgoError != nil {
		fmt.Println(MgoError.Error())
	} else {
		fmt.Println(num)
	}
	// find - one
	var one map[string]interface{}
	MgoError = c.Find(map[string]string{"name": "黃忠"}).One(&one)
	if MgoError != nil {
		fmt.Println(MgoError.Error())
	} else {
		fmt.Println(one)
	}
	// find - all
	var all []map[string]interface{}
	MgoError = c.Find(map[string]string{"name": "黃忠"}).All(&all)
	if MgoError != nil {
		fmt.Println(MgoError.Error())
	} else {
		fmt.Println(all)
	}
}