go get go.mongodb.org/mongo-driver/mongo
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func connect(uri, username, passward string) (*mongo.Client, error) {
// 连接参数
clientOptions := options.Client().ApplyURI(uri).SetAuth(options.Credential{
Username: username,
Password: passward,
})
// 连接
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
return nil, err
}
// 检查连接
err = client.Ping(context.Background(), readpref.Primary())
if err != nil {
return nil, err
}
// 连接数据库并返回
return client, nil
}
func main() {
client, err := connect("mongodb://localhost:27017", "root", "1234")
if err != nil {
panic(err)
}
db := client.Database("db_test")
fmt.Printf("数据库%s连接成功\r\n", db.Name())
}
err = client.Disconnect(context.TODO())
if err != nil {
panic(err)
}
fmt.Println("断开连接成功")
在MongoDB中,数据以BSON(Binary JSON)的格式存储。BSON是一种二进制表示的JSON文档形式
D是有序的BSON文档
E是D中的一个元素
M是无序的BSON文档
A是有序的BSON数组
type User struct {
Name string `bson:"name"`
Age int16 `basn:"age"`
}
func insert(users *mongo.Collection) error {
// 插入一条BAON文档
res1, err := users.InsertOne(context.Background(), User{Name: "tom", Age: 18})
if err != nil {
return err
}
fmt.Println("id: ", res1.InsertedID)
// 插入多条BAON文档
res2, err := users.InsertMany(context.Background(), []interface{}{User{Name: "jack", Age: 17}, User{Name: "lisa", Age: 20}})
if err != nil {
return err
}
fmt.Println("ids: ", res2.InsertedIDs)
return nil
}
func search(users *mongo.Collection) error {
// 查询条件:name == jack
filter := bson.M{"name": "jack"}
// 查询一个
res := users.FindOne(context.Background(), filter)
user := User{}
err := res.Decode(&user)
if err != nil {
return err
}
fmt.Println("user: ", user)
// 查询多个
cursor, err := users.Find(context.Background(), filter)
if err != nil {
return err
}
ress := make([]User, 0)
err = cursor.All(context.Background(), &ress)
if err != nil {
return err
}
fmt.Println("users: ", ress)
return nil
}
func update(users *mongo.Collection) error {
// 查询条件:name == jack
filter := bson.M{"name": "jack"}
// 修改一个
res, err := users.UpdateOne(context.Background(), filter, bson.M{"$set": bson.M{"age": 10}})
if err != nil {
return err
}
fmt.Printf("matched count %d, modified count %d\r\n", res.MatchedCount, res.ModifiedCount)
// 修改多个
res, err = users.UpdateMany(context.Background(), filter, bson.M{"$set": bson.M{"age": 10}})
if err != nil {
return err
}
fmt.Printf("matched count %d, modified count %d\r\n", res.MatchedCount, res.ModifiedCount)
return nil
}
func delete(users *mongo.Collection) error {
// 查询条件:name == jack
filter := bson.M{"name": "jack"}
// 删除一个
res, err := users.DeleteOne(context.Background(), filter)
if err != nil {
return err
}
fmt.Printf("deleted count %d\r\n", res.DeletedCount)
// 删除多个
res, err = users.DeleteMany(context.Background(), filter)
if err != nil {
return err
}
fmt.Printf("deleted count %d\r\n", res.DeletedCount)
return nil
}