文章目录
连接数据库
cpp
复制代码
package main
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
func main() {
//连接数据库
var (
client = MgoCli()
db *mongo.Database
collection *mongo.Collection
)
db = client.Database("my_db")
collection = db.Collection("my_collection")
collection = collection
}
插入数据库
插入一条数据
cpp
复制代码
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"time"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
// 插入一条数据
type ExecTime struct {
StartTime int64 `bson:"startTime"`
EndTime int64 `bson:"endTime"`
}
type LogRecord struct {
JobName string `bson:"jobName"`
Command string `bson:"command"`
Err string `bson:"err"`
Content string `bson:"content"`
Tp ExecTime
}
func main() {
var (
client = MgoCli()
err error
collection *mongo.Collection
iResult *mongo.InsertOneResult
id primitive.ObjectID
)
collection = client.Database("my_db").Collection("my_collection")
logRecord := LogRecord{
JobName: "job1",
Command: "echo 1",
Err: "",
Content: "1",
Tp: ExecTime{
StartTime: time.Now().Unix(),
EndTime: time.Now().Unix() + 10,
},
}
if iResult, err = collection.InsertOne(context.TODO(), logRecord); err != nil {
fmt.Println(err)
return
}
id = iResult.InsertedID.(primitive.ObjectID)
fmt.Println("自增 ID", id.Hex())
}
批量插入数据
cpp
复制代码
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"time"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
// 插入一条数据
type ExecTime struct {
StartTime int64 `bson:"startTime"`
EndTime int64 `bson:"endTime"`
}
type LogRecord struct {
JobName string `bson:"jobName"`
Command string `bson:"command"`
Err string `bson:"err"`
Content string `bson:"content"`
Tp ExecTime
}
func main() {
var (
client = MgoCli()
err error
collection *mongo.Collection
result *mongo.InsertManyResult
id primitive.ObjectID
)
collection = client.Database("my_db").Collection("test")
result, err = collection.InsertMany(context.TODO(), []interface{}{
LogRecord{
JobName: "job1",
Command: "echo 1",
Err: "",
Content: "1",
Tp: ExecTime{
StartTime: time.Now().Unix(),
EndTime: time.Now().Unix() + 10,
},
},
LogRecord{
JobName: "job1",
Command: "echo 1",
Err: "",
Content: "1",
Tp: ExecTime{
StartTime: time.Now().Unix(),
EndTime: time.Now().Unix() + 10,
},
},
})
if err != nil {
log.Fatal(err)
}
if result == nil {
log.Fatal("result nil")
}
for _, v := range result.InsertedIDs {
id = v.(primitive.ObjectID)
fmt.Println("自增 ID", id.Hex())
}
}
查询数据
cpp
复制代码
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
// 插入一条数据
type ExecTime struct {
StartTime int64 `bson:"startTime"`
EndTime int64 `bson:"endTime"`
}
type LogRecord struct {
JobName string `bson:"jobName"`
Command string `bson:"command"`
Err string `bson:"err"`
Content string `bson:"content"`
Tp ExecTime
}
type FindByJobName struct {
JobName string `bson:"jobName"`
}
func main() {
var (
client = MgoCli()
err error
collection *mongo.Collection
cursor *mongo.Cursor
)
collection = client.Database("my_db").Collection("table1")
cond := FindByJobName{JobName: "job multil"}
findOptions := options.Find().SetSkip(0).SetLimit(2)
if cursor, err = collection.Find(context.TODO(), cond, findOptions); err != nil {
fmt.Println(err)
return
}
defer func() {
if err = cursor.Close(context.TODO()); err != nil {
log.Fatal(err)
}
}()
for cursor.Next(context.TODO()) {
var lr LogRecord
if cursor.Decode(&lr) != nil {
fmt.Println(err)
return
}
fmt.Println(lr)
}
var results []LogRecord
if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err)
}
for _, result := range results {
fmt.Println(result)
}
}
用 BSON 进行复合查询
聚合查询
cpp
复制代码
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
func main() {
client := MgoCli()
collection := client.Database("my_db").Collection("table1")
groupStage := mongo.Pipeline{
bson.D{
{"$group", bson.D{
{"_id", "$jobName"},
{"countJob", bson.D{
{"$sum", 1},
}},
}},
},
}
cursor, err := collection.Aggregate(context.TODO(), groupStage)
if err != nil {
log.Fatal(err)
}
defer func() {
err = cursor.Close(context.TODO()) // 修正关闭游标的错误处理
if err != nil {
log.Fatal(err)
}
}()
var results []bson.M
err = cursor.All(context.TODO(), &results)
if err != nil {
log.Fatal(err)
}
for _, result := range results {
fmt.Println(result)
}
}
更新数据
cpp
复制代码
package main
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
type UpdateByJobName struct {
Command string `bson:"command"`
Content string `bson:"content"`
}
func main() {
var (
client = MgoCli()
collection *mongo.Collection
err error
uResult *mongo.UpdateResult
)
collection = client.Database("my_db").Collection("table1")
filter := bson.M{"jobName": "job multil"}
// bson.M{"$inc",bson.M{"age",-1,}}
//bson.M{"$push",bson.M{"interests","Golang",}}
//bson.M{"$pull",bson.M{"interests","Golang",}}
update := bson.M{"$set": UpdateByJobName{
Command: "byModel",
Content: "model",
}}
if uResult, err = collection.UpdateMany(context.TODO(), filter, update); err != nil {
log.Fatal(err)
}
log.Println(uResult.MatchedCount)
}
删除数据
cpp
复制代码
package main
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"time"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
type DeleteCond struct {
BeforeCond TimeBeforeCond `bson:"tp.startTime"`
}
// startTime小于某时间,使用这种方式可以对想要进行的操作($set、$group等)提前定义
type TimeBeforeCond struct {
BeforeTime int64 `bson:"$lt"`
}
func main() {
var (
client = MgoCli()
collection *mongo.Collection
err error
uResult *mongo.DeleteResult
delCond *DeleteCond
)
collection = client.Database("my_db").Collection("table1")
//删除jobName为job0的数据
delCond = &DeleteCond{
BeforeCond: TimeBeforeCond{
BeforeTime: time.Now().Unix()}}
if uResult, err = collection.DeleteMany(context.TODO(),
delCond); err != nil {
log.Fatal(err)
}
log.Println(uResult.DeletedCount)
}
cpp
复制代码
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var mgoCli *mongo.Client
func initDb() {
var err error
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = mgoCli.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
func MgoCli() *mongo.Client {
if mgoCli == nil {
initDb()
}
return mgoCli
}
// 分组
type Group struct {
Group interface{} `bson:"$group"`
}
// 求和
type Sum struct {
Sum interface{} `bson:"$sum"`
}
func main() {
var (
client = MgoCli()
collection *mongo.Collection
err error
cursor *mongo.Cursor
)
collection = client.Database("my_db").Collection("table1")
groupStage := []Group{}
groupStage = append(groupStage, Group{
Group: bson.D{
{"_id", "$jobName"},
{"countJob", Sum{Sum: 1}},
},
})
if cursor, err = collection.Aggregate(context.TODO(),
groupStage); err != nil {
log.Fatal(err)
}
defer func() {
if err = cursor.Close(context.TODO()); err != nil {
log.Fatal(err)
}
}()
var results []bson.M
if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err)
}
for _, result := range results {
fmt.Println(result)
}
}