mongodb客户端的golang实现
mgo很有可能作为golang的标准库
mgo文档
连接
1 | package database |
登录
1 | Session, err = mgo.Dial(config.MongoDB.Host + ":" + config.MongoDB.Port) |
增删改查
上述是建立连接,并执行操作
insert
1 | type d struct { |
select
1 | type d struct { |
delete
1 | // 为了代码的可读性,没有验证错误error |
update
修改第一条,修改此条全部内容
1
2
3
4
5
6//struct 的键需要大写
collection.Update(bson.M{"x": 3}, struct {
X int
Y int
Z int
}{3, 4, 5})修改第一条,修改此条部分内容
1
collection.Update(bson.M{"x": 0}, bson.M{"$set": bson.M{"y": 1}})
修改多条,只能修改每一条的部分内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14changeLog, err := collection.UpdateAll(bson.M{"x": 6}, bson.M{"$set": bson.M{"y": 1}})
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("Matched:", changeLog.Matched)
fmt.Println("Removed:", changeLog.Removed)
fmt.Println("Updated:", changeLog.Updated)
fmt.Println("UpsertedId:", changeLog.UpsertedId)
// 结果
> go run test.go
Matched: 2
Removed: 0
Updated: 2
UpsertedId: <nil>