0、结构体
type Student struct { // _id 不用带入 Name string Age int }
1、连接
驱动 :github.com/mongodb/mongo-go-driver
1、普通连接
client , err := mongo.Connect( context.TODO(), options.Client().ApplyURI("mongodb://192.168.6.249:27017")) if err != nil { fmt.Printf("mongodb connect failed, err : %s\n", err) return } defer func() { if err = client.Disconnect(context.TODO()); err != nil { fmt.Printf("mongodb disconnect failed, err : %s\n", err) return } }()
2、连接池连接
2、插入
1、插入单条
collection := client.Database("erp").Collection("Student") // 插入一条 s1 := Student{Age: 12, Name: "hello"} insertResult, err := collection.InsertOne(context.TODO(), s1) if err != nil { fmt.Printf("insert mongodb failed , err : %s\n", err) return }
fmt.Println("insert a single document: ", insertResult)
2、插入多条
s2 := Student{Age: 13, Name: "world"} insertDocs := []interface{}{s1, s2} many, err := collection.InsertMany(context.TODO(), insertDocs) fmt.Println(many) // &{[ObjectID("62fefa56a4e8957a0d611caf") ObjectID("62fefa56a4e8957a0d611cb0")]}
3、删除
1、单个删除
// 删除单个文档 [有多条也仅仅只删除一条] deleteResult1, err := collection.DeleteOne(context.TODO(), bson.M{"age": 12}) if err != nil { fmt.Printf("delete one doc failed, err : %s\n", err) return } fmt.Printf("delete %v doc", deleteResult1.DeletedCount) // 删除文档的个数
2、删除多个
// 删除所有文档
_, err = collection.DeleteMany(context.TODO(), bson.M{})
if err != nil {
fmt.Printf("delete many doc failed, err : %s\n", err)
return
}
4、查询
1、单个查询
var stu Student filter := bson.M{"age": 13} collection.FindOne(context.TODO(), filter).Decode(&stu) fmt.Printf("stu ==> %+v\n", stu)
2、多个查询
// 查询多个文档 findOptions := options.Find() findOptions.SetLimit(3) var results []*Student // 把 bson.D{{}} 作为一个 filter 来匹配所有文档 cur, err :=collection.Find(context.TODO(), bson.D{{}}, findOptions) if err != nil { fmt.Printf("find mongodb failed, err : %s\n", err) return } // 查找多个文档返回一个光标 // 遍历游标允许我们一次解码一个文档 for cur.Next(context.TODO()) { // 创建一个值,将单个文档解码为该值 var stu Student err := cur.Decode(&stu) if err != nil { fmt.Printf("mongodb decode, err : %s\n", err) return } results = append(results, &stu) } defer cur.Close(context.TODO()) for _, v := range results { fmt.Printf("%v\n", v) }
标签:err,mongodb,fmt,golang,context,Printf,TODO From: https://www.cnblogs.com/dogHuang/p/16601648.html