This page looks best with JavaScript enabled

mgo 连接 MongoDB 数据库的使用实例

 ·  ☕ 2 min read · 👀... views
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// mgotest project main.go
package main

import (
	"fmt"
	"time"

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

type User struct {
	Id        bson.ObjectId `bson:"_id"`
	Username  string        `bson:"name"`
	Pass      string        `bson:"pass"`
	Regtime   int64         `bson:"regtime"`
	Interests []string      `bson:"interests"`
}

const URL = "127.0.0.1:27017"

var c *mgo.Collection
var session *mgo.Session

var GlobalMgoSession, err = mgo.Dial(URL)

func (user User) ToString() string {
	return fmt.Sprintf("%#v", user)
}

// func init() {
// 	session = GlobalMgoSession.Clone()
// 	// session, _ = mgo.Dial(URL)
// 	//切换到数据库
// 	db := session.DB("blog")
// 	//切换到collection
// 	c = db.C("mgotest")
// }

//新增数据
func add() {
	session = GlobalMgoSession.Clone()
	// session, _ = mgo.Dial(URL)
	//切换到数据库
	db := session.DB("blog")
	//切换到collection
	c = db.C("mgotest")
	defer session.Close()
	stu1 := new(User)
	stu1.Id = bson.NewObjectId()
	stu1.Username = "stu1_name"
	stu1.Pass = "stu1_pass"
	stu1.Regtime = time.Now().Unix()
	stu1.Interests = []string{"象棋", "游泳", "跑步"}
	err := c.Insert(stu1)
	if err == nil {
		fmt.Println("插入成功")
	} else {
		fmt.Println(err.Error())
		defer panic(err)
	}
}

//查询
func find() {
	session = GlobalMgoSession.Clone()
	// session, _ = mgo.Dial(URL)
	//切换到数据库
	db := session.DB("blog")
	//切换到collection
	c = db.C("mgotest")
	defer session.Close()
	var users []User
	//    c.Find(nil).All(&users)
	c.Find(bson.M{"name": "stu1_name"}).All(&users)
	for _, value := range users {
		fmt.Println(value.ToString())
	}
	//根据ObjectId进行查询
	idStr := "599a46ca1d8ec1068da6c620"
	objectId := bson.ObjectIdHex(idStr)
	user := new(User)
	c.Find(bson.M{"_id": objectId}).One(user)
	fmt.Println(user)
}

//根据id进行修改
func update() {
	session = GlobalMgoSession.Clone()
	// session, _ = mgo.Dial(URL)
	//切换到数据库
	db := session.DB("blog")
	//切换到collection
	c = db.C("mgotest")
	interests := []string{"象棋", "游泳", "跑步"}
	err := c.Update(bson.M{"_id": bson.ObjectIdHex("599a46f71d8ec106b29c6681")}, bson.M{"$set": bson.M{
		"name":      "修改后的name",
		"pass":      "修改后的pass",
		"regtime":   time.Now().Unix(),
		"interests": interests,
	}})
	if err != nil {
		fmt.Println("修改失败")
	} else {
		fmt.Println("修改成功")
	}
}

//删除
func del() {
	session = GlobalMgoSession.Clone()
	// session, _ = mgo.Dial(URL)
	//切换到数据库
	db := session.DB("blog")
	//切换到collection
	c = db.C("mgotest")
	err := c.Remove(bson.M{"_id": bson.ObjectIdHex("599a4ea31d8ec10749c5f119")})
	if err != nil {
		fmt.Println("删除失败" + err.Error())
	} else {
		fmt.Println("删除成功")
	}
}
func main() {
	add()
	find()
	update()
	del()
}
Share on

睡沙发の沙皮狗
WRITTEN BY
睡沙发の沙皮狗
👨‍💻 Backend Developer/📚 Learner/🚀 Opensource enthusiast

 

What's on this Page