go语言操作mongodb
代码
// mongodb CRUD
// ctx bson.D ?
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Student struct {
Name string
City string
Score float32
}
func CheckError(err error, line int){
if err != nil {
fmt.Println("error line:", line)
log.Fatal(err)
}
}
func query(ctx context.Context, collection *mongo.Collection) {
// https://blog.csdn.net/ootw/article/details/115902576, 需要规范化的编写才不会飘黄
sort := bson.D{{Key:"score", Value:1}} // 排序, 1升序, -1降序
filter := bson.D{{Key:"score", Value:bson.D{{Key:"$gt", Value:3}}}} // 过滤条件 score > 3
findOption := options.Find()
findOption.SetSort(sort)
findOption.SetLimit(10) // 最多返回10个
findOption.SetSkip(0) // 跳过前三个
cursor, err := collection.Find(ctx, filter, findOption)
if err != nil {
log.Fatal(err)
}
// 关闭迭代器
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var doc Student
err := cursor.Decode(&doc)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s %s %.2f\n", doc.Name, doc.City, doc.Score)
}
}
func create(ctx context.Context, collection *mongo.Collection) {
// 插入一个文档
doc := Student{
Name: "啊哈",
City: "香港",
Score: 86,
}
ret, _ := collection.InsertOne(ctx, doc)
// CheckError(err, 64)
// 每个doc都会有一个全世界唯一的ID(时间+空间唯一)
fmt.Printf("insert id %v\n", ret.InsertedID)
// 插入多个doc
docs := []interface{}{
Student{
Name: "小C",
City: "上海",
Score: 90,
},
Student{
Name: "小D",
City: "杭州",
Score: 89,
},
}
manyRes, err := collection.InsertMany(ctx, docs)
fmt.Printf("insert many ids %v\n", manyRes.InsertedIDs)
CheckError(err, 85)
}
func update(ctx context.Context, collection *mongo.Collection) {
fileter := bson.D{{Key:"city", Value:"杭州"}}
update := bson.D{{Key:"$inc", Value: bson.D{{Key: "score", Value: 89}}}}
res, err := collection.UpdateMany(ctx, fileter, update)
CheckError(err, 96)
fmt.Printf("update %d doc \n", res.ModifiedCount)
}
func delete(ctx context.Context, collection *mongo.Collection) {
filter := bson.D{{Key:"name", Value: "小D"}}
res, err := collection.DeleteMany(ctx, filter)
CheckError(err, 105)
fmt.Printf("delete %d doc \n", res.DeletedCount)
}
func main() {
// 不懂
ctx := context.Background()
// 设置客户端连接配置
clientOptions := options.Client().ApplyURI("mongodb://172.30.1.128:27017")
clientOptions.SetConnectTimeout(time.Second)
clientOptions.SetAuth(options.Credential{Username: "admin", Password: "Tck151##a", AuthSource: "admin"})
// 连接到mongodb
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
// 释放连接
defer client.Disconnect(ctx)
collection := client.Database("test").Collection("student")
query(ctx, collection)
// create(ctx, collection)
// update(ctx, collection)
// delete(ctx, collection)
}
``
go语言之操作mongodb