1. 项目地址:
    go.mongodb.org/mongo-driver/mongo

  2. 使用:

     package main
    
     import (
         "context"
         "fmt"
         "go.mongodb.org/mongo-driver/bson"
         "go.mongodb.org/mongo-driver/bson/primitive"
         "go.mongodb.org/mongo-driver/event"
         "go.mongodb.org/mongo-driver/mongo"
         "go.mongodb.org/mongo-driver/mongo/options"
         "log"
         "time"
     )
    
     type People struct {
         Id       primitive.ObjectID `bson:"_id,omitempty"`
         Name     string             `bson:"name"`
         Age      int                `bson:"age"`
         CreateAt time.Time          `bson:"createAt"`
     }
    
     func main() {
         ctx := context.TODO()
         // 记录日志
         var logMonitor = event.CommandMonitor{
             Started: func(ctx context.Context, startedEvent *event.CommandStartedEvent) {
                 log.Printf("[开始执行] 执行语句: %s\n",
                     startedEvent.Command.String())
             },
             Succeeded: func(ctx context.Context, succeededEvent *event.CommandSucceededEvent) {
                 log.Printf("[执行成功] 执行命令: %s 执行时间: %dms\n",
                     succeededEvent.CommandName, succeededEvent.Duration.Milliseconds())
             },
             Failed: func(ctx context.Context, failedEvent *event.CommandFailedEvent) {
                 log.Printf("[执行失败] 执行命令: %s 执行时间: %dms\n",
                     failedEvent.CommandName, failedEvent.Duration.Milliseconds())
             },
         }
         client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:123456@10.0.0.11:27017,10.0.0.12:27017,10.0.0.13:27017").SetConnectTimeout(5*time.Second).SetMonitor(&logMonitor))
         if err != nil {
             panic(err)
         }
         // 选择数据库
         db := client.Database("test")
         // 创建集合
         if err := db.CreateCollection(ctx, "myCo"); err != nil {
             panic(err)
         }
         // 选择集合(表)
         collection := db.Collection("coTest")
         // 新增一条记录
         resultInertOne, err := collection.InsertOne(ctx, People{
             Name:     "lee",
             Age:      30,
             CreateAt: time.Now(),
         })
         if err != nil {
             panic(err)
         }
         insertId := resultInertOne.InsertedID.(primitive.ObjectID)
         fmt.Println(insertId)
         // 新增多条记录
         resultInsertMany, err := collection.InsertMany(ctx, []interface{}{
             People{
                 Name:     "lee",
                 Age:      30,
                 CreateAt: time.Now(),
             },
             People{
                 Name:     "zhangsan",
                 Age:      18,
                 CreateAt: time.Now(),
             },
         })
         if err != nil {
             panic(err)
         }
         for _, item := range resultInsertMany.InsertedIDs {
             fmt.Println(item.(primitive.ObjectID))
         }
         // 删除一条记录
         resultDeleteOne, err := collection.DeleteOne(ctx, bson.M{"name": "lee"})
         if err != nil {
             panic(err)
         }
         fmt.Println(resultDeleteOne.DeletedCount)
         // 删除多条记录
         resultDeleteMany, err := collection.DeleteMany(ctx, bson.M{"name": "lee"})
         if err != nil {
             panic(err)
         }
         fmt.Println(resultDeleteMany.DeletedCount)
         // 更新一条记录
         resultUpdateOne, err := collection.UpdateOne(ctx, bson.M{"name": "zhangsan"}, bson.M{"$set": bson.M{"name": "lee"}})
         if err != nil {
             panic(err)
         }
         fmt.Println(resultUpdateOne.MatchedCount)
         // 更新多条记录
         resultUpdateMany, err := collection.UpdateMany(ctx, bson.M{"name": "zhangsan"}, bson.M{"$set": bson.M{"name": "lee"}})
         if err != nil {
             panic(err)
         }
         fmt.Println(resultUpdateMany.MatchedCount)
         // 查询是否存在记录
         count, err := collection.CountDocuments(ctx, bson.M{
             "name": "lee",
         })
         if err != nil {
             panic(err)
         }
         fmt.Println("count:", count)
         // 查询一条记录
         resultFindOne := collection.FindOne(ctx, bson.M{
             "name": "zhangsan",
             "$or": bson.A{
                 bson.M{
                     "age": bson.M{"$lt": 20},
                 },
                 bson.M{
                     "name": bson.M{"$regex": "/^zhang/"},
                 },
             },
         })
         if err := resultFindOne.Err(); err != nil {
             panic(err)
         }
         var peopleFindOne People
         if err := resultFindOne.Decode(&peopleFindOne); err != nil {
             panic(err)
         }
         fmt.Println(peopleFindOne)
         fmt.Println(peopleFindOne.CreateAt.Local().Format("2006-01-02 15:04:05")) // 查询时间,注意加上 .Local()
         // 查询多条记录
         cursorFindMany, err := collection.Find(ctx, bson.M{
             "name": "zhangsan",
             "$or": bson.A{
                 bson.M{
                     "age": bson.M{"$lt": 20},
                 },
                 bson.M{
                     "name": bson.M{"$regex": "/^zhang/"},
                 },
             },
         },
             options.Find().SetProjection(bson.M{"_id": 0}), // 忽略 _id 字段
             options.Find().SetLimit(2),
             options.Find().SetSkip(1),
             options.Find().SetSort(bson.M{
                 "age": 1,
             }),
         )
         if err != nil {
             panic(err)
         }
         defer cursorFindMany.Close(ctx) // 关闭游标
         var peopleFindMany []People
         if err = cursorFindMany.All(ctx, &peopleFindMany); err != nil {
             panic(err)
         }
         for _, item := range peopleFindMany {
             fmt.Println(item)
             fmt.Println(item.CreateAt.Local().Format("2006-01-02 15:04:05")) // 查询时间,注意加上 .Local()
         }
         // 聚合查询
         startTime := time.Date(2019, 8, 11, 12, 0, 0, 0, time.Local)
         endTime := time.Now()
         pipeline := []bson.M{
             {
                 "$match": bson.M{
                     "createAt": bson.M{
                         "$gte": startTime,
                         "$lte": endTime,
                     },
                 },
             },
             {
                 "$group": bson.M{
                     "_id": "$name",
                     "total": bson.M{
                         "$sum": 1,
                     },
                     "age": bson.M{
                         "$first": "$age",
                     },
                 },
             },
             {
                 "$sort": bson.M{
                     "age": -1,
                 },
             },
         }
         cursorAggregate, err := collection.Aggregate(ctx, pipeline)
         if err != nil {
             panic(err)
         }
         var resultAggregate []bson.M
         if err = cursorAggregate.All(ctx, &resultAggregate); err != nil {
             panic(err)
         }
         for _, item := range resultAggregate {
             fmt.Println(item)
         }
         // 事务操作
         if err := db.Client().UseSession(ctx, func(sessionContext mongo.SessionContext) error {
             // 注意:
             //         1. 这里所有的写操作均是以 sessionContext 做为上下文的
             //        2. 提交和回滚操作的上下文需要使用 ctx
             if err := sessionContext.StartTransaction(); err != nil {
                 return err
             }
             // 新增一条记录
             _, err := db.Collection("trans").InsertOne(sessionContext, bson.M{"a": 3})
             if err != nil {
                 sessionContext.AbortTransaction(ctx)
                 return err
             }
             // 更新一条记录
             _, err = db.Collection("trans").UpdateOne(sessionContext, bson.M{"a": 3}, bson.M{"$inc": bson.M{"a": 1}})
             if err != nil {
                 sessionContext.AbortTransaction(ctx)
                 return err
             }
             sessionContext.CommitTransaction(ctx)
             return nil
         }); err != nil {
             panic(err)
         }
     }
文档更新时间: 2024-04-20 10:57   作者:lee