开发环境
$ docker run -d --name mongo \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=654321 \
mongo:4.0
go.mod 设置
go 1.14
require go.mongodb.org/mongo-driver v1.4.6
连接
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
}
连接和集合
// database
database := client.Database("my_db")
// collection
collection := database.Collection("my_collection")
log.Println(collection.Name())
插入一条数据
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
// database
database := client.Database("my_db")
// collection
collection := database.Collection("my_collection")
s := &Student{
Name: "张三",
Gender: "男",
Age: 20,
}
res, err := collection.InsertOne(context.TODO(), s)
if err != nil {
log.Fatal(err)
}
docId := res.InsertedID.(primitive.ObjectID)
recordId := docId.Hex()
log.Println("insert one ID str is :", recordId)
}
插入多条数据
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
collection := client.Database("my_db").Collection("my_collection")
s1 := &Student{
Name: "李四",
Gender: "男",
Age: 18,
}
s2 := &Student{
Name: "王五",
Gender: "女",
Age: 30,
}
res, err := collection.InsertMany(context.TODO(), []interface{}{s1, s2})
if err != nil {
log.Fatal(err)
}
log.Println("insert manyID is :", res)
}
查找单条数据
package main
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
collection := client.Database("my_db").Collection("my_collection")
filter := bson.M{"name": "张三"}
res := collection.FindOne(ctx, filter)
if res == nil || res.Err() != nil {
log.Fatal("find one error ", res.Err().Error())
}
var s Student
err = res.Decode(&s)
if err != nil {
log.Fatal("find one failed error is ", err)
}
log.Println("find one success, res is ", s)
}
查找多条
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
ID string `bson:"_id,omitempty"`
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
collection := client.Database("my_db").Collection("my_collection")
filter := bson.M{"age": bson.M{"$gte": 20}}
cursor, err := collection.Find(ctx, filter)
if err != nil {
log.Fatal("find error ", err)
return
}
defer cursor.Close(context.Background())
list := make([]Student, 0, cursor.RemainingBatchLength())
for cursor.Next(context.Background()) {
var s Student
err := cursor.Decode(&s)
if err != nil {
log.Println("decode error is ", err)
continue
}
list = append(list, s)
}
log.Println("find result ", list)
}
分页查找
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
ID string `bson:"_id,omitempty"`
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
collection := client.Database("my_db").Collection("my_collection")
filter := bson.M{"age": bson.M{"$gte": 0}}
sort := bson.D{{"age", -1}}
findOptions := options.Find().SetSort(sort)
//从第1页获取,每次获取5条
page := 1
size := 5
skipTmp := int64((page - 1) * size)
limitTmp := int64(size)
findOptions.Skip = &skipTmp
findOptions.Limit = &limitTmp
cursor, err := collection.Find(ctx, filter, findOptions)
defer cursor.Close(context.Background())
if err != nil {
log.Fatal("limit page error is ", err)
}
for cursor.Next(context.Background()) {
var s Student
err := cursor.Decode(&s)
if err != nil {
log.Println("data decode error", err)
continue
}
log.Println(s)
}
}
更新单条数据
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
ID string `bson:"_id,omitempty"`
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
collection := client.Database("my_db").Collection("my_collection")
filter := bson.M{"name": "李四"}
value := bson.M{"$set": bson.M{
"age": 25}}
res, err := collection.UpdateOne(ctx, filter, value)
if err != nil {
log.Println("update data err", err)
return
}
log.Println("update count", res.ModifiedCount)
}
修改多条数据
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
ID string `bson:"_id,omitempty"`
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
collection := client.Database("my_db").Collection("my_collection")
var names = []string{"张三", "李四"}
filter := bson.M{"name": bson.M{"$in": names}}
value := bson.M{"$set": bson.M{"age": 22}}
result, err := collection.UpdateMany(ctx, filter, value)
if err != nil {
log.Fatal("update many error", err)
}
log.Println("update count ", result.ModifiedCount)
}
删除
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Student struct {
ID string `bson:"_id,omitempty"`
Name string `bson:"name"` // 名字
Gender string `bson:gender` // 性别
Age int8 `bson:"age"` // 年龄
}
func main() {
clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
SetConnectTimeout(5 * time.Second).
SetAuth(options.Credential{Username: "admin", Password: "654321"})
ctx := context.TODO()
client, err := mongo.Connect(ctx, clientOptions)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
log.Println("mongodb connect success")
collection := client.Database("my_db").Collection("my_collection")
filter := bson.D{{"name", "张三"}}
res, err := collection.DeleteOne(ctx, filter)
if err != nil {
log.Fatal(err)
}
log.Println("delete count", res.DeletedCount)
}