博客网址:www.shicoder.top
微信:kj11011029
欢迎加群聊天 :452380935
之前的博客中将mongodb的自带命令进行讲解,这次我们结合go的包mongo-driver
进行代码实现
连接操作
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
log.Fatal(err)
}
fmt.Println("connect successful")
- 选择数据库和集合
collection := client.Database("test").Collection("aaa")
CRUD
- 插入
// 方式一
insertResult, err := collection.InsertOne(context.TODO(), bson.D{{"name","shilinkun2"},{"Age",15}})
// 方式二
// 但这种有个缺陷
/*
结构体的字段必须首字母大写,同时在插入的时候,会
自动将字段全部转为小写,因该是可以修改,但目前还不知
怎么操作hhh
*/
type People struct {
Name string
Age int
}
p := People{
"shilinkun1",
15,
}
// 类似 db.aaa.insertOne({"name":"shilinkun1","age":15})
insertResult, err := collection.InsertOne(context.TODO(),p)
- 更新
filter := bson.D{
{"name","shilinkun"},
}
update := bson.D{
{"$inc",bson.D{{"Age",1}}},
}
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
- 查找
// 单个查询
var result interface{}
err = collection.FindOne(context.TODO(),bson.D{}).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
// 带条件单个查询
var result interface{}
filter := bson.D{
{"name","shilinkun"},
}
err = collection.FindOne(context.TODO(),filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
// 多个查询
cur,err := collection.Find(context.TODO(),bson.D{})
for cur.Next(context.TODO()) {
fmt.Println(cur.Current.String())
}
// 带sort、limit、skip条件
sort := bson.D{{"title",1}}
findOptions := options.Find().SetSort(sort).SetLimit(4).SetSkip(5)
cur,err := collection.Find(context.TODO(),bson.D{},findOptions)
for cur.Next(context.TODO()) {
fmt.Println(cur.Current.String())
}
// 带过滤条件查询
filter := bson.D{
{"author.age",bson.D{{"$lt",25}}},
}
cur,err := collection.Find(context.TODO(),filter)
for cur.Next(context.TODO()) {
fmt.Println(cur.Current.String())
}
- 删除
filter := bson.D{
{"title","book-5"},
}
count,err:= collection.DeleteMany(context.TODO(),filter)
fmt.Println(count)
- 向集合中一条数据中的一个数组中添加/删除一个元素
filter := bson.D{
{"title","book-0"},
}
update := bson.D{
{"$push",bson.D{{"tag","mongodb1"}}},
}
_, err = collection.UpdateOne(context.TODO(), filter, update)
操作前:
{"_id": {"$oid":"6271102510f566b3b1a8dba5"},"title": "book-0","type": "technology","tag": ["mongodb","developer"]
操作后
{"_id": {"$oid":"6271102510f566b3b1a8dba5"},"title": "book-0","type": "technology","tag": ["mongodb","developer","mongodb1"]
同样删除为
filter := bson.D{
{"title","book-0"},
}
update := bson.D{
{"$pull",bson.D{{"tag","mongodb1"}}},
}
_, err = collection.UpdateOne(context.TODO(), filter, update)
聚合操作
- 单阶段
groupStage := bson.D{
{"$group", bson.D{
{"_id", "$author.name"},
{"pop", bson.D{{"$sum", "$favCount"}}},
}},
}
//groupStage := bson.D{
// {"$group",bson.D{
// {"_id","null"},
// {"count",bson.D{{"$sum",1}}},
// {"pop",bson.D{{"$sum","$favCount"}}},
// {"avg",bson.D{{"$avg","$favCount"}}},
// }},
//}
//
//groupStage := bson.D{
// {"$project",bson.D{
// {"name","$title"},
// {"_id",0},
// {"type",1},
// {"author",1},
// }},
//}
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{groupStage})
if err != nil {
log.Fatal(err)
}
cursor, err := collection.Aggregate(context.TODO(),mongo.Pipeline{groupStage})
if err != nil {
log.Fatal(err)
}
for cursor.Next(context.TODO()) {
fmt.Println(cursor.Current.String())
}
- 多阶段
groupStage1 := bson.D{
{"$match",bson.D{
{"type","travel"},
}},
}
groupStage2 := bson.D{
{"$project",bson.D{
{"name","$title"},
{"_id",0},
{"type",1},
{"author",1},
}},
}
cursor, err := collection.Aggregate(context.TODO(),mongo.Pipeline{groupStage1,groupStage2})
if err != nil {
log.Fatal(err)
}
for cursor.Next(context.TODO()) {
fmt.Println(cursor.Current.String())
}
评论 (0)