连接数据库
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
}
插入数据库
插入一条数据
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())
}
批量插入数据
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())
}
}
查询数据
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 进行复合查询
聚合查询
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)
}
}
更新数据
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"}
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)
}
删除数据
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"`
}
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")
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)
}
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)
}
}