关于Go和MongoDB的简单例子

355 阅读1分钟

Golang和MongoDB都是快速应用开发和构建规模化事物的完美组合。它们都有原生的功能,使你能够专注于你的应用程序。在选择数据库时,要确保MongoDB符合你的要求,因为它不是一个一刀切的解决方案。阅读关于其设计和使用案例的官方文档。在这篇文章中,我们将从安装到构建一个CRUD。

安装并启动MongoDB

在Mac上安装MongoDB

brew update
brew install mongodb

创建数据目录

在你第一次启动MongoDB之前,创建一个目录,mongod 进程将写入其中。默认情况下,这是在**/data/db**。如果你创建了一个不同的目录,在启动mongod 进程时在dbpath 选项中指定。

设置权限

在运行mongod 之前,确保将要运行它的用户账户对该目录有读和写权限。

# change owner of everything in /data to current user
sudo chown -R $USER /data/db

# allow user to have read/write access
sudo chmod -R u+rw /data/db

运行MongoDB服务器

mongod

这就是了!然而,如果你改变了默认的目录,你将不得不指定它,像这样。mongod --dbpath /path/to/dir

连接到外壳

通常情况下,你会通过你的应用程序进行连接,但如果你想连接到你刚刚运行的MongoDB服务器,请执行MongoDB shell客户端。

mongo

转到

注意:本节仍在开发中

获取用于Go的Mongo驱动。

go get gopkg.in/mgo.v2

CRUD示例

package main

import (
	"fmt"
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Game struct {
	Winner       string    `bson:"winner"`
	OfficialGame bool      `bson:"official_game"`
	Location     string    `bson:"location"`
	StartTime    time.Time `bson:"start"`
	EndTime      time.Time `bson:"end"`
	Players      []Player  `bson:"players"`
}

type Player struct {
	Name   string    `bson:"name"`
	Decks  [2]string `bson:"decks"`
	Points uint8     `bson:"points"`
	Place  uint8     `bson:"place"`
}

func NewPlayer(name, firstDeck, secondDeck string, points, place uint8) Player {
	return Player{
		Name:   name,
		Decks:  [2]string{firstDeck, secondDeck},
		Points: points,
		Place:  place,
	}
}

var isDropMe = true

func main() {
	Host := []string{
		"127.0.0.1:27017",
		// replica set addrs...
	}
	const (
		Username   = "YOUR_USERNAME"
		Password   = "YOUR_PASS"
		Database   = "YOUR_DB"
		Collection = "YOUR_COLLECTION"
	)
	session, err := mgo.DialWithInfo(&mgo.DialInfo{
		Addrs: Host,
		// Username: Username,
		// Password: Password,
		// Database: Database,
		// DialServer: func(addr *mgo.ServerAddr) (net.Conn, error) {
		// 	return tls.Dial("tcp", addr.String(), &tls.Config{})
		// },
	})
	if err != nil {
		panic(err)
	}
	defer session.Close()

	game := Game{
		Winner:       "Dave",
		OfficialGame: true,
		Location:     "Austin",
		StartTime:    time.Date(2015, time.February, 12, 04, 11, 0, 0, time.UTC),
		EndTime:      time.Now(),
		Players: []Player{
			NewPlayer("Dave", "Wizards", "Steampunk", 21, 1),
			NewPlayer("Javier", "Zombies", "Ghosts", 18, 2),
			NewPlayer("George", "Aliens", "Dinosaurs", 17, 3),
			NewPlayer("Seth", "Spies", "Leprechauns", 10, 4),
		},
	}

	if isDropMe {
		err = session.DB("test").DropDatabase()
		if err != nil {
			panic(err)
		}
	}

	// Collection
	c := session.DB(Database).C(Collection)

	// Insert
	if err := c.Insert(game); err != nil {
		panic(err)
	}

	// Find and Count
	player := "Dave"
	gamesWon, err := c.Find(bson.M{"winner": player}).Count()
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s has won %d games.\n", player, gamesWon)

	// Find One (with Projection)
	var result Game
	err = c.Find(bson.M{"winner": player, "location": "Austin"}).Select(bson.M{"official_game": 1}).One(&result)
	if err != nil {
		panic(err)
	}
	fmt.Println("Is game in Austin Official?", result.OfficialGame)

	// Find All
	var games []Game
	err = c.Find(nil).Sort("-start").All(&games)
	if err != nil {
		panic(err)
	}
	fmt.Println("Number of Games", len(games))

	// Update
	newPlayer := "John"
	selector := bson.M{"winner": player}
	updator := bson.M{"$set": bson.M{"winner": newPlayer}}
	if err := c.Update(selector, updator); err != nil {
		panic(err)
	}

	// Update All
	info, err := c.UpdateAll(selector, updator)
	if err != nil {
		panic(err)
	}
	fmt.Println("Updated", info.Updated)

	// Remove
	info, err = c.RemoveAll(bson.M{"winner": newPlayer})
	if err != nil {
		panic(err)
	}
	fmt.Println("Removed", info.Removed)
}