mgo类

package module
v0.0.0-...-d3125e7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 14, 2024 License: Apache-2.0 Imports: 19 Imported by: 0

README

Qmgo

Build Status Coverage Status Go Report Card GitHub release GoDoc

English | 简体中文

Qmgo

Qmgo 是一款Go语言的MongoDB driver,它基于MongoDB 官方 driver 开发实现,同时使用更易用的接口设计,比如参考mgo (比如mgo的链式调用)。

  • Qmgo让您以更优雅的姿势使用MongoDB的新特性。

  • Qmgo是从mgo迁移到新MongoDB driver的第一选择,对代码的改动影响最小。

要求

  • Go 1.10 及以上。
  • MongoDB 2.6 及以上。

功能

  • 文档的增删改查, 均支持官方driver支持的所有options
  • Sortlimitcountselectdistinct
  • 事务
  • Hooks
  • 自动化更新的默认和定制fields
  • 预定义操作符
  • 聚合Aggregate、索引操作、cursor
  • validation tags 基于tag的字段验证
  • 可自定义插件化编程

安装

推荐方式是使用go mod,通过在源码中import github.com/qiniu/qmgo 来自动安装依赖。

当然,通过下面方式同样可行:

go get github.com/qiniu/qmgo

Usage

  • 开始

    import并新建连接

    import(
        "context"
    
        "github.com/qiniu/qmgo"
    )
    
    ctx := context.Background()
    client, err := qmgo.NewClient(ctx, &qmgo.Config{Uri: "mongodb://localhost:27017"})
    db := client.Database("class")
    coll := db.Collection("user")
    
    

    如果你的连接是指向固定的 database 和 collection,我们推荐使用下面的更方便的方法初始化连接,后续操作都基于cli而不用再关心 database 和 collection

    cli, err := qmgo.Open(ctx, &qmgo.Config{Uri: "mongodb://localhost:27017", Database: "class", Coll: "user"})
    

    后面都会基于cli来举例,如果你使用第一种传统的方式进行初始化,根据上下文,将cli替换成clientdbcoll即可

    在初始化成功后,请defer来关闭连接

    defer func() {
        if err = cli.Close(ctx); err != nil {
            panic(err)
        }
    }()
    
  • 创建索引

    做操作前,我们先初始化一些数据:

    
    type UserInfo struct {
        Name   string `bson:"name"`
        Age    uint16 `bson:"age"`
        Weight uint32 `bson:"weight"`
    }
    
    var userInfo = UserInfo{
        Name:   "xm",
        Age:    7,
        Weight: 40,
    }
    

    创建索引

    cli.CreateOneIndex(context.Background(), options.IndexModel{Key: []string{"name"}})
    cli.CreateIndexes(context.Background(), []options.IndexModel{{Key: []string{"id2", "id3"}}})
    
  • 插入一个文档

    // insert one document
    result, err := cli.InsertOne(ctx, userInfo)
    
  • 查找一个文档

        // find one document
    one := UserInfo{}
    err = cli.Find(ctx, bson.M{"name": userInfo.Name}).One(&one)
    
  • 删除文档

    err = cli.Remove(ctx, bson.M{"age": 7})
    
  • 插入多条数据

    // multiple insert
    var userInfos = []UserInfo{
        UserInfo{Name: "a1", Age: 6, Weight: 20},
        UserInfo{Name: "b2", Age: 6, Weight: 25},
        UserInfo{Name: "c3", Age: 6, Weight: 30},
        UserInfo{Name: "d4", Age: 6, Weight: 35},
        UserInfo{Name: "a1", Age: 7, Weight: 40},
        UserInfo{Name: "a1", Age: 8, Weight: 45},
    }
    result, err = cli.Collection.InsertMany(ctx, userInfos)
    
  • 批量查找、SortLimit

    // find all 、sort and limit
    batch := []UserInfo{}
    cli.Find(ctx, bson.M{"age": 6}).Sort("weight").Limit(7).All(&batch)
    
  • Count

    count, err := cli.Find(ctx, bson.M{"age": 6}).Count()
    
  • Update

    // UpdateOne one
    err := cli.UpdateOne(ctx, bson.M{"name": "d4"}, bson.M{"$set": bson.M{"age": 7}})
    
    // UpdateAll
    result, err := cli.UpdateAll(ctx, bson.M{"age": 6}, bson.M{"$set": bson.M{"age": 10}})
    
  • Select

    err := cli.Find(ctx, bson.M{"age": 10}).Select(bson.M{"age": 1}).One(&one)
    
  • Aggregate

    matchStage := bson.D{{"$match", []bson.E{{"weight", bson.D{{"$gt", 30}}}}}}
    groupStage := bson.D{{"$group", bson.D{{"_id", "$name"}, {"total", bson.D{{"$sum", "$age"}}}}}}
    var showsWithInfo []bson.M
    err = cli.Aggregate(context.Background(), Pipeline{matchStage, groupStage}).All(&showsWithInfo)
    
  • 建立连接时支持所有 mongoDB 的Options

    poolMonitor := &event.PoolMonitor{
        Event: func(evt *event.PoolEvent) {
            switch evt.Type {
            case event.GetSucceeded:
                fmt.Println("GetSucceeded")
            case event.ConnectionReturned:
                fmt.Println("ConnectionReturned")
            }
        },
    }
    
    opt := options.Client().SetPoolMonitor(poolMonitor)  // more options use the chain options.
    cli, err := Open(ctx, &Config{Uri: URI, Database: DATABASE, Coll: COLL}, opt)
    
    
  • 事务

    有史以来最简单和强大的事务, 同时还有超时和重试等功能:

    callback := func(sessCtx context.Context) (interface{}, error) {
        // 重要:确保事务中的每一个操作,都使用传入的sessCtx参数
        if _, err := cli.InsertOne(sessCtx, bson.D{{"abc", int32(1)}}); err != nil {
            return nil, err
        }
        if _, err := cli.InsertOne(sessCtx, bson.D{{"xyz", int32(999)}}); err != nil {
            return nil, err
        }
        return nil, nil
    }
    result, err = cli.DoTransaction(ctx, callback)
    

    关于事务的更多内容

  • 预定义操作符

    // aggregate
    matchStage := bson.D{{operator.Match, []bson.E{{"weight", bson.D{{operator.Gt, 30}}}}}}
    groupStage := bson.D{{operator.Group, bson.D{{"_id", "$name"}, {"total", bson.D{{operator.Sum, "$age"}}}}}}
    var showsWithInfo []bson.M
    err = cli.Aggregate(context.Background(), Pipeline{matchStage, groupStage}).All(&showsWithInfo)
    
  • Hooks

    Qmgo 灵活的 hooks:

    type User struct {
        Name         string    `bson:"name"`
        Age          int       `bson:"age"`
    }
    func (u *User) BeforeInsert(ctx context.Context) error {
        fmt.Println("before insert called")
        return nil
    }
    func (u *User) AfterInsert(ctx context.Context) error {
        fmt.Println("after insert called")
        return nil
    }
    
    u := &User{Name: "Alice", Age: 7}
    _, err := cli.InsertOne(context.Background(), u)
    

    Hooks 详情介绍

  • 自动化更新fields

    Qmgo支持2种方式来自动化更新特定的字段

    • 默认 fields

    在文档结构体里注入 field.DefaultField, Qmgo 会自动在更新和插入操作时更新 createAtupdateAt and _id field的值.

    type User struct {
        field.DefaultField `bson:",inline"`
    
        Name string `bson:"name"`
        Age  int    `bson:"age"`
    }
    
    u := &User{Name: "Lucas", Age: 7}
    _, err := cli.InsertOne(context.Background(), u)
    // tag为createAt、updateAt 和 _id 的字段会自动更新插入
    
    • Custom fields

    可以自定义field名, Qmgo 会自动在更新和插入操作时更新他们.

    type User struct {
        Name string `bson:"name"`
        Age  int    `bson:"age"`
    
        MyId         string    `bson:"myId"`
        CreateTimeAt time.Time `bson:"createTimeAt"`
        UpdateTimeAt int64     `bson:"updateTimeAt"`
    }
    // 指定自定义field的field名
    func (u *User) CustomFields() field.CustomFieldsBuilder {
        return field.NewCustom().SetCreateAt("CreateTimeAt").SetUpdateAt("UpdateTimeAt").SetId("MyId")
    }
    
    u := &User{Name: "Lucas", Age: 7}
    _, err := cli.InsertOne(context.Background(), u)
    // CreateTimeAt、UpdateTimeAt and MyId 会自动更新并插入DB 
    
    // 假设Id和ui已经初始化
    err = cli.ReplaceOne(context.Background(), bson.M{"_id": Id}, &ui)
    // UpdateTimeAt 会被自动更新
    

    例子介绍

    自动化 fields 详情介绍

  • Validation tags 基于tag的字段验证

    功能基于go-playground/validator实现。

    所以Qmgo支持所有go-playground/validator 的struct验证规则,比如:

    type User struct {
        FirstName string            `bson:"fname"`
        LastName  string            `bson:"lname"`
        Age       uint8             `bson:"age" validate:"gte=0,lte=130" `    // Age must in [0,130]
        Email     string            `bson:"e-mail" validate:"required,email"` //  Email can't be empty string, and must has email format
        CreateAt  time.Time         `bson:"createAt" validate:"lte"`          // CreateAt must lte than current time
        Relations map[string]string `bson:"relations" validate:"max=2"`       // Relations can't has more than 2 elements
    }
    

    本功能只对以下API有效: InsertOne、InsertyMany、Upsert、UpsertId、ReplaceOne

  • 插件化编程

    • 实现以下方法

      func Do(ctx context.Context, doc interface{}, opType operator.OpType, opts ...interface{}) error{
        // do anything
      }
      
    • 调用middleware包的Register方法,注入Do Qmgo会在支持的操作执行前后调用Do

      middleware.Register(Do)
      

    Example

    Qmgo的hook、自动更新field和validation tags都基于plugin的方式实现

qmgo vs go.mongodb.org/mongo-driver

下面我们举一个多文件查找、sortlimit的例子, 说明qmgomgo的相似,以及对go.mongodb.org/mongo-driver的改进

官方Driver需要这样实现

// go.mongodb.org/mongo-driver
// find all 、sort and limit
findOptions := options.Find()
findOptions.SetLimit(7)  // set limit
var sorts D
sorts = append(sorts, E{Key: "weight", Value: 1})
findOptions.SetSort(sorts) // set sort

batch := []UserInfo{}
cur, err := coll.Find(ctx, bson.M{"age": 6}, findOptions)
cur.All(ctx, &batch)

Qmgomgo更简单,而且实现相似:

// qmgo
// find all 、sort and limit
batch := []UserInfo{}
cli.Find(ctx, bson.M{"age": 6}).Sort("weight").Limit(7).All(&batch)

// mgo
// find all 、sort and limit
coll.Find(bson.M{"age": 6}).Sort("weight").Limit(7).All(&batch)

Qmgo vs mgo

Qmgo 和 Mgo 的差异

Contributing

非常欢迎您对Qmgo的任何贡献,非常感谢您的帮助!

沟通交流:

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrQueryNotSlicePointer 当查询结果参数不是指向切片的指针时返回该错误
	ErrQueryNotSlicePointer = errors.New("result argument must be a pointer to a slice")
	// ErrQueryNotSliceType 当结果参数不是切片地址时返回该错误
	ErrQueryNotSliceType = errors.New("result argument must be a slice address")
	// ErrQueryResultTypeInconsistent 当查询结果类型与mongodb的值类型不相等时返回该错误
	ErrQueryResultTypeInconsistent = errors.New("result type is not equal mongodb value type")
	// ErrQueryResultValCanNotChange 当查询结果的值不能被更改时返回该错误
	ErrQueryResultValCanNotChange = errors.New("the value of result can not be changed")
	// ErrNoSuchDocuments 当没有找到任何文档时返回这个错误
	ErrNoSuchDocuments = mongo.ErrNoDocuments
	// ErrTransactionRetry:如果事务需要重试则返回该错误
	ErrTransactionRetry = errors.New("retry transaction")
	// ErrTransactionNotSupported 当事务不被支持时返回该错误
	ErrTransactionNotSupported = errors.New("transaction not supported")
	// ErrNotSupportedUsername 当用户名无效时返回该错误
	ErrNotSupportedUsername = errors.New("username not supported")
	// ErrNotSupportedPassword 当密码无效时返回该错误
	ErrNotSupportedPassword = errors.New("password not supported")
	// ErrNotValidSliceToInsert 当插入参数不是一个有效的切片时返回该错误
	ErrNotValidSliceToInsert = errors.New("must be valid slice to insert")
	// ErrReplacementContainUpdateOperators 当替换文档包含更新操作符时返回错误
	ErrReplacementContainUpdateOperators = errors.New("replacement document cannot contain keys beginning with '$'")
)

Functions

func SplitSortField

func SplitSortField(field string) (key string, sort int32)

SplitSortField handle sort symbol: "+"/"-" in front of field if "+", return sort as 1 if "-", return sort as -1

func X取当前时间

func X取当前时间() time.Time

现在返回当前时间的毫秒级别

func X是否为无文档错误

func X是否为无文档错误(错误 error) bool

IsErrNoDocuments 检查 err 是否表示没有文档,包括mongo-go-driver库的错误和qmgo自定义错误 已弃用,直接调用 if err == ErrNoSuchDocuments 或 if err == mongo.ErrNoDocuments 即可

func X是否为重复键错误

func X是否为重复键错误(错误 error) bool

IsDup check if err is mongo E11000 (duplicate err)。

func X比较版本号

func X比较版本号(版本号1 string, 版本号2 string) (int, error)

CompareVersions 比较两个版本号字符串(即由点分隔的正整数)。比较操作会以两者中精度较低的那个为准。例如,3.2 被视为等于 3.2.11,而 3.2.0 则被视为小于 3.2.11。

如果 version1 大于 version2,则返回一个正整数;如果 version1 小于 version2,则返回一个负整数;如果 version1 等于 version2,则返回 0。

func X生成对象ID

func X生成对象ID() primitive.ObjectID

NewObjectID 生成一个新的 ObjectID。 注意:它生成 objectID 的方式与 mgo 不同。

Types

type A

type A = bson.A

A 是 bson.A 的别名

type Aggregate

type Aggregate struct {
	// contains filtered or unexported fields
}

Aggregate 是对聚合的处理句柄

func (*Aggregate) Iter弃用

func (a *Aggregate) Iter弃用() CursorI

Iter 返回聚合后的游标 已弃用,请使用 Cursor

func (*Aggregate) X取一条

func (a *Aggregate) X取一条(结果指针 interface{}) error

One 通过从聚合中迭代游标,并将当前文档解码到结果中。

func (*Aggregate) X取全部

func (a *Aggregate) X取全部(结果指针 interface{}) error

All 遍历从聚合中获取的游标,并将每个文档解码到结果中。

func (*Aggregate) X取结果集

func (a *Aggregate) X取结果集() CursorI

Cursor 返回聚合后的游标

type AggregateI

type AggregateI interface {
	X取全部(results interface{}) error
	X取一条(result interface{}) error
	Iter弃用() CursorI // 已弃用,请改用Cursor
	X取结果集() CursorI
}

AggregateI 定义了聚合的接口

type Bulk

type Bulk struct {
	// contains filtered or unexported fields
}

Bulk 用于批量操作的上下文,这些批量操作将被一次性发送到数据库进行批量写入。

Bulk 不支持并发安全使用。

注意事项:

当前,在一个批量操作内部的单个操作不会触发中间件或钩子。

与原始 mgo 不同,qmgo 实现的 Bulk 在不原生支持批量操作的老版本 MongoDB 服务器上,并不会模拟逐个执行批量操作。

只有官方驱动所支持的操作才会被公开提供,这就是为什么方法中缺少 InsertMany 的原因。

func (*Bulk) X删除

func (b *Bulk) X删除(删除条件 interface{}) *Bulk

RemoveAll 函数用于批量执行,它将一个 RemoveAll 操作添加到待处理队列中。

func (*Bulk) X删除一条

func (b *Bulk) X删除一条(删除条件 interface{}) *Bulk

Remove 函数用于批量执行时,将一个 Remove 操作加入队列。

func (*Bulk) X删除并按ID

func (b *Bulk) X删除并按ID(删除ID interface{}) *Bulk

RemoveId 为批量执行队列一个RemoveId操作。

func (*Bulk) X执行

func (b *Bulk) X执行(上下文 context.Context) (*BulkResult, error)

Run 执行收集到的所有操作,以单一的批量操作方式。

若调用成功,将会重置 Bulk。如果返回错误,则内部的操作队列保持不变, 该队列中包含已成功执行和未成功执行的操作。

func (*Bulk) X插入

func (b *Bulk) X插入(待插入文档 interface{}) *Bulk

InsertOne 将一个 InsertOne 操作排队以进行批量执行。

func (*Bulk) X更新

func (b *Bulk) X更新(更新条件 interface{}, 更新内容 interface{}) *Bulk

UpdateAll 将一个UpdateAll操作添加到队列中以进行批量执行。 更新操作应包含操作符

func (*Bulk) X更新一条

func (b *Bulk) X更新一条(更新条件 interface{}, 更新内容 interface{}) *Bulk

UpdateOne 将一个UpdateOne操作排队以进行批量执行。 更新内容应包含操作符

func (*Bulk) X更新并按ID

func (b *Bulk) X更新并按ID(更新ID interface{}, 更新内容 interface{}) *Bulk

UpdateId 将一个UpdateId操作加入队列以进行批量执行。 更新操作应包含操作符

func (*Bulk) X更新或插入

func (b *Bulk) X更新或插入(更新条件 interface{}, 更新内容 interface{}) *Bulk

Upsert 在批量执行中安排一个Upsert操作。 替换项应为不包含操作符的文档

func (*Bulk) X更新或插入一条

func (b *Bulk) X更新或插入一条(更新条件 interface{}, 更新内容 interface{}) *Bulk

UpsertOne 函数用于将一个 UpsertOne 操作加入到批量执行的队列中。 更新操作应当包含操作符

func (*Bulk) X更新或插入并按ID

func (b *Bulk) X更新或插入并按ID(更新ID interface{}, 更新内容 interface{}) *Bulk

UpsertId 队列一个 UpsertId 操作以便进行批量执行。 替换内容应为不包含操作符的文档。

func (*Bulk) X设置有序执行

func (b *Bulk) X设置有序执行(开启有序 bool) *Bulk

SetOrdered 标记批量操作为有序或无序。

若标记为有序,当其中一次独立写入操作失败后,后续的写入操作将不再继续。 默认设置为有序。

type BulkResult

type BulkResult struct {
	// 插入的文档数量。
	InsertedCount int64

	// 在更新和替换操作中,满足过滤条件的文档数量。
	MatchedCount int64

	// update和replace操作修改的文档数量。
	ModifiedCount int64

	// 删除的文档数量。
	DeletedCount int64

	// update和replace操作中更新或替换的文档数量。
	UpsertedCount int64

	// 一个映射表,键为操作索引,值为每个已更新(upserted)文档的 _id。
	UpsertedIDs map[int64]interface{}
}

BulkResult 是 Bulk.Run 操作返回的结果类型。

type Change

type Change struct {
	X更新替换    interface{} // 更新/替换文档
	X是否替换    bool        // 是否替换整个文档而不是更新
	X是否删除    bool        // 是否移除找到的文档而非更新
	X未找到是否插入 bool        // Whether to insert in case the document isn't found, take effect when Remove is false
	X是否返回新文档 bool        // 是否应返回修改后的文档而非旧文档,仅在Remove为false时生效
}

Change 用于在 Query.Apply 方法中执行 findAndModify 命令所需的字段。

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client 创建用于连接 MongoDB 的客户端

func X创建客户端

func X创建客户端(上下文 context.Context, 配置 *Config, 可选选项 ...options.ClientOptions) (客户端 *Client, 错误 error)

NewClient 创建 Qmgo MongoDB 客户端

func (*Client) X事务

func (c *Client) X事务(上下文 context.Context, 回调函数 func(sessCtx context.Context) (interface{}, error), 可选选项 ...*options.TransactionOptions) (interface{}, error)

DoTransaction do whole transaction in one function precondition: - version of mongoDB server >= v4.0 - Topology of mongoDB server is not Single At the same time, please pay attention to the following

  • make sure all operations in callback use the sessCtx as context parameter
  • if operations in callback takes more than(include equal) 120s, the operations will not take effect,
  • if operation in callback return qmgo.ErrTransactionRetry, the whole transaction will retry, so this transaction must be idempotent
  • if operations in callback return qmgo.ErrTransactionNotSupported,
  • If the ctx parameter already has a Session attached to it, it will be replaced by this session.

func (*Client) X关闭

func (c *Client) X关闭(上下文 context.Context) error

Close关闭与此Client关联的拓扑结构的所有套接字连接。

func (*Client) X创建Session

func (c *Client) X创建Session(可选选项 ...*options.SessionOptions) (*Session, error)

Session 在客户端创建一个会话 注意,在操作完成后关闭会话

func (*Client) X取版本号

func (c *Client) X取版本号() string

ServerVersion 获取MongoDB服务器的版本,如4.4.0

func (*Client) X是否存活

func (c *Client) X是否存活(超时时长 int64) error

Ping:确认连接是否存活

func (*Client) X设置数据库

func (c *Client) X设置数据库(数据库名称 string, 可选选项 ...*options.DatabaseOptions) *Database

创建与数据库的连接

type Collection

type Collection struct {
	// contains filtered or unexported fields
}

Collection 是对 MongoDB 集合的一个引用句柄

func (*Collection) EnsureIndexes弃用

func (c *Collection) EnsureIndexes弃用(ctx context.Context, uniques []string, indexes []string) (err error)

EnsureIndexes 已弃用 建议使用 CreateIndexes / CreateOneIndex 以获得更多的功能) EnsureIndexes 在集合中创建唯一索引和非唯一索引 索引的组合方式与 CreateIndexes 不同: 如果 uniques/indexes 是 []string{"name"},表示创建名为 "name" 的索引 如果 uniques/indexes 是 []string{"name,-age","uid"},表示首先创建复合索引:name 和 -age(按 name 升序、age 降序),然后创建一个名为 uid 的单字段索引

func (*Collection) X创建批量执行

func (c *Collection) X创建批量执行() *Bulk

Bulk 返回一个新的上下文,用于批量执行操作的准备工作。

func (*Collection) X删除

func (c *Collection) X删除(上下文 context.Context, 删除条件 interface{}, 可选选项 ...opts.RemoveOptions) (删除结果 *DeleteResult, 错误 error)

RemoveAll executes a delete command to delete documents from the collection. If filter is bson.M{},all ducuments in Collection will be deleted Reference: https://docs.mongodb.com/manual/reference/command/delete/

func (*Collection) X删除一条

func (c *Collection) X删除一条(上下文 context.Context, 删除条件 interface{}, 可选选项 ...opts.RemoveOptions) (错误 error)

Remove executes a delete command to delete at most one document from the collection. if filter is bson.M{},DeleteOne will delete one document in collection Reference: https://docs.mongodb.com/manual/reference/command/delete/

func (*Collection) X删除全部索引

func (c *Collection) X删除全部索引(上下文 context.Context) (错误 error)

DropAllIndexes 从集合中删除所有索引,但保留_id字段的索引 如果集合上只有_id字段的索引,函数调用将报告错误

func (*Collection) X删除并按ID

func (c *Collection) X删除并按ID(上下文 context.Context, 删除ID interface{}, 可选选项 ...opts.RemoveOptions) (错误 error)

RemoveId 执行一个删除命令,从集合中最多删除一个文档。

func (*Collection) X删除索引

func (c *Collection) X删除索引(上下文 context.Context, 索引s []string) error

DropIndex 删除集合中的索引,需要删除的索引应与输入的索引一致 索引indexes为[]string{"name"}表示删除名为"name"的索引 索引indexes为[]string{"name","-age"}表示删除由"name"和"-age"组成的复合索引

func (*Collection) X删除集合

func (c *Collection) X删除集合(上下文 context.Context) error

DropCollection 删除集合 即使集合不存在,此操作也是安全的

func (*Collection) X取副本

func (c *Collection) X取副本() (*mongo.Collection, error)

CloneCollection 创建一个 Collection 的副本

func (*Collection) X取变更流

func (c *Collection) X取变更流(上下文 context.Context, 管道 interface{}, 可选选项 ...*opts.ChangeStreamOptions) (*mongo.ChangeStream, error)

Watch 返回一个变更流,用于接收相应集合的所有变更。有关变更流的更多信息,请参阅 https://docs.mongodb.com/manual/changeStreams/

func (*Collection) X取集合名

func (c *Collection) X取集合名() string

GetCollectionName 返回集合名称

func (*Collection) X插入

func (c *Collection) X插入(上下文 context.Context, 待插入文档 interface{}, 可选选项 ...opts.InsertOneOptions) (插入结果 *InsertOneResult, 错误 error)

InsertOne 将一个文档插入集合中 如果 opts 中设置了 InsertHook,那么钩子会作用于它,否则钩子尝试将文档当作钩子处理 参考:https://docs.mongodb.com/manual/reference/command/insert/

func (*Collection) X插入多个

func (c *Collection) X插入多个(上下文 context.Context, 待插入文档 interface{}, 可选选项 ...opts.InsertManyOptions) (插入结果 *InsertManyResult, 错误 error)

InsertMany 执行一个插入命令,将多个文档插入到集合中。 如果 opts 中设置了 InsertHook,则在该 hook 上执行操作;否则尝试将 doc 作为 hook 使用 参考文献:https://docs.mongodb.com/manual/reference/command/insert/

func (*Collection) X更新

func (c *Collection) X更新(上下文 context.Context, 更新条件 interface{}, 更新内容 interface{}, 可选选项 ...opts.UpdateOptions) (更新结果 *UpdateResult, 错误 error)

UpdateAll 执行一个更新命令,用于更新集合中的文档。 如果没有文档被更新,UpdateResult 中的 matchedCount 为 0 参考文献:https://docs.mongodb.com/manual/reference/operator/update/

func (*Collection) X更新一条

func (c *Collection) X更新一条(上下文 context.Context, 更新条件 interface{}, 更新内容 interface{}, 可选选项 ...opts.UpdateOptions) (错误 error)

UpdateOne 执行一个更新命令,用于在集合中最多更新一条文档。 参考文献:https://docs.mongodb.com/manual/reference/operator/update/

func (*Collection) X更新并按ID

func (c *Collection) X更新并按ID(上下文 context.Context, 更新ID interface{}, 更新内容 interface{}, 可选选项 ...opts.UpdateOptions) (错误 error)

UpdateId 执行一个更新命令,用于在集合中最多更新一个文档。 参考文献:https://docs.mongodb.com/manual/reference/operator/update/

func (*Collection) X更新或插入

func (c *Collection) X更新或插入(上下文 context.Context, 更新条件 interface{}, 更新内容 interface{}, 可选选项 ...opts.UpsertOptions) (更新结果 *UpdateResult, 错误 error)

Upsert:如果过滤条件匹配,则更新一条文档;如果不匹配,则插入一条文档。当过滤条件无效时,将返回错误。 replacement 参数必须是一个用于替换所选文档的文档对象,不能为 nil,并且不能包含任何更新操作符。 参考文献:https://docs.mongodb.com/manual/reference/operator/update/ 如果 replacement 中包含 "_id" 字段,并且该文档已存在,请确保初始化时使用现有 id(即使启用了 Qmgo 的默认字段特性)。 否则,将会出现 "(不可变字段)'_id' 被修改" 的错误。

func (*Collection) X更新或插入并按ID

func (c *Collection) X更新或插入并按ID(上下文 context.Context, 更新ID interface{}, 更新内容 interface{}, 可选选项 ...opts.UpsertOptions) (更新结果 *UpdateResult, 错误 error)

UpsertId 如果_id匹配则更新一条文档,如果不匹配则插入一条文档,并将_id注入到该文档中 replacement参数必须是一个用于替换所选文档的文档,不能为nil 且不能包含任何更新操作符 参考文献:https://docs.mongodb.com/manual/reference/operator/update/

func (*Collection) X替换一条

func (c *Collection) X替换一条(上下文 context.Context, 替换条件 interface{}, 替换内容 interface{}, 可选选项 ...opts.ReplaceOptions) (错误 error)

ReplaceOne 执行一个更新命令,最多替换集合中的一个文档。 如果opts中的UpdateHook已设置,则在该hook上执行操作,否则尝试将doc作为hook处理 预期doc的类型应为用户定义的文档类型

func (*Collection) X查询

func (c *Collection) X查询(上下文 context.Context, 查询条件 interface{}, 可选选项 ...opts.FindOptions) QueryI

Find find by condition filter,return QueryI

func (*Collection) X索引一条

func (c *Collection) X索引一条(上下文 context.Context, 索引 opts.IndexModel) error

CreateOneIndex 创建一个索引 如果 opts.IndexModel 中的 Key 为 []string{"name"},表示创建名为 "name" 的索引 如果 opts.IndexModel 中的 Key 为 []string{"name", "-age"},表示创建组合索引:包含 name 和 -age(按 name 正序、age 倒序)

func (*Collection) X索引多条

func (c *Collection) X索引多条(上下文 context.Context, 索引s []opts.IndexModel) (错误 error)

CreateIndexes 在集合中创建多个索引 如果opts.IndexModel中的Key为[]string{"name"},表示创建名为"name"的索引 如果opts.IndexModel中的Key为[]string{"name","-age"},表示创建复合索引:按"name"和"-age"(降序)字段 进一步详细解释: ```go CreateIndexes 函数用于在指定的数据库集合中创建多个索引。 当 opts.IndexModel 中的 Key 字段是一个包含单个元素 "name" 的字符串切片时,例如 []string{"name"}, 这意味着将根据字段 "name" 创建一个升序索引。 若 opts.IndexModel 中的 Key 字段是一个包含两个元素 "name" 和 "-age" 的字符串切片,例如 []string{"name", "-age"}, 这表示将创建一个复合索引,其中先按 "name" 字段升序排序,然后按 "age" 字段降序排序。

func (*Collection) X聚合

func (c *Collection) X聚合(上下文 context.Context, 聚合管道 interface{}, 可选选项 ...opts.AggregateOptions) AggregateI

Aggregate 对集合执行聚合命令,并返回一个 AggregateI 以便获取结果文档。

type Config

type Config struct {
	// URI 示例: [mongodb://][用户名:密码@]主机1[:端口1][,主机2[:端口2],...][/数据库][?选项]
	// URI 参考文档: https://docs.mongodb.com/manual/reference/connection-string/
	// 这段Go语言代码的注释是关于MongoDB数据库连接字符串(URI)的格式说明:
	// - `mongodb://`:表示URI的协议部分,表明这是用于连接MongoDB服务器的地址。
	// - `[user:pass@]`:可选的认证信息部分,其中`user`代表用户名,`pass`为经过编码的密码。
	// - `host1[:port1][,host2[:port2],...]`:必填的服务器地址和端口部分,可以指定一个或多个服务器及对应端口,用逗号分隔。
	// - `[/database]`:可选的数据库名称部分,用于指定默认连接的数据库。
	// - `[?options]`:可选的连接参数部分,以问号开头,后面跟随一系列键值对(key=value&key=value...),用于设置额外的连接选项。
	Uri      string `json:"uri"`
	Database string `json:"database"`
	Coll     string `json:"coll"`
	// ConnectTimeoutMS 指定一个用于建立到服务器连接的超时时间。
	//	如果设置为0,将不使用超时。
	//	默认值是30秒。
	ConnectTimeoutMS *int64 `json:"connectTimeoutMS"`
	// MaxPoolSize 指定驱动程序连接池中允许的每个服务器最大连接数。
	// 如果该值为0,则会被设置为 math.MaxInt64,
	// 默认值是100。
	MaxPoolSize *uint64 `json:"maxPoolSize"`
	// MinPoolSize 指定驱动程序与每个服务器连接池中允许的最小连接数。如果该值不为零,
	// 则会后台维护每个服务器的连接池,确保其大小不低于最小值。也可以通过 "minPoolSize" URI 选项(例如 "minPoolSize=100")进行设置。
	// 默认值为 0。
	MinPoolSize *uint64 `json:"minPoolSize"`
	// SocketTimeoutMS 指定了在返回网络错误之前,驱动程序将等待套接字读写操作返回的时间。如果该值为0,则表示不使用超时,套接字操作可能会无限期阻塞。默认值为300,000毫秒。
	SocketTimeoutMS *int64 `json:"socketTimeoutMS"`
	// ReadPreference 决定哪些服务器被认为适合读取操作。
	// 默认设置为 PrimaryMode
	ReadPreference *ReadPref `json:"readPreference"`
	// 可用于在配置 Client 时提供身份验证选项。
	Auth *Credential `json:"auth"`
}

Config 是初始 MongoDB 实例的配置

type Credential

type Credential struct {
	AuthMechanism string `json:"authMechanism"`
	AuthSource    string `json:"authSource"`
	Username      string `json:"username"`
	Password      string `json:"password"`
	PasswordSet   bool   `json:"passwordSet"`
}

Credential 可用于在配置 Client 时提供认证选项。

AuthMechanism: 指定用于认证的机制。支持的值包括 "SCRAM-SHA-256", "SCRAM-SHA-1", "MONGODB-CR", "PLAIN", "GSSAPI", "MONGODB-X509" 和 "MONGODB-AWS"。也可以通过 "authMechanism" URI 选项设置(例如:"authMechanism=PLAIN")。更多信息请参阅: https://docs.mongodb.com/manual/core/authentication-mechanisms/. AuthSource: 用于认证的数据库名称。对于 MONGODB-X509、GSSAPI 和 PLAIN,该值默认为 "$external", 对于其他机制,默认为 "admin"。也可以通过 "authSource" URI 选项设置(例如:"authSource=otherDb")。

Username: 认证所需的用户名。也可以通过 URI 以 username:password 的形式在第一个 @ 字符前设置。例如, 对于用户名为 "user",密码为 "pwd",主机为 "localhost:27017" 的情况,URI 应为 "mongodb://user:pwd@localhost:27017"。 对于 X509 认证,这是可选的,并且如果不指定,将从客户端证书中提取。

Password: 认证所需的密码。对于 X509 认证,不应指定密码;对于 GSSAPI 认证,密码是可选的。

PasswordSet: 对于 GSSAPI,如果指定了密码(即使密码为空字符串),则必须为 true;如果没有指定密码, 表示应从运行进程的上下文中获取密码,则应为 false。对于其他认证机制,此字段将被忽略。

type Cursor

type Cursor struct {
	// contains filtered or unexported fields
}

Cursor struct define

func (*Cursor) X下一个

func (c *Cursor) X下一个(result interface{}) bool

Next 获取此游标的下一个文档。如果未发生错误且游标未被耗尽,则返回true。

func (*Cursor) X关闭

func (c *Cursor) X关闭() error

Close 关闭此游标。在调用 Close 后,不得再调用 Next 和 TryNext。 当游标对象不再使用时,应主动关闭它。

func (*Cursor) X取全部

func (c *Cursor) X取全部(results interface{}) error

All 方法遍历游标并对每个文档进行解码,将结果存入 results 参数。results 参数必须是指向切片的指针。 推荐在结构体 Query 或 Aggregate 中使用 All() 方法。

func (*Cursor) X取错误

func (c *Cursor) X取错误() error

Err 返回Cursor的最后一个错误,如果没有发生错误,则返回nil

type CursorI

type CursorI interface {
	X下一个(result interface{}) bool
	X关闭() error
	X取错误() error
	X取全部(results interface{}) error
}

CursorI:游标接口

type D

type D = bson.D

D 是 bson.D 的别名

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database 是一个指向 MongoDB 数据库的句柄

func (*Database) X创建集合

func (db *Database) X创建集合(上下文 context.Context, 集合名称 string, 可选选项 ...options.CreateCollectionOptions) error

CreateCollection 执行创建命令,用于在服务器上明确创建一个指定名称的新集合。如果要创建的集合已存在,则此方法将返回 mongo.CommandError。该方法需要驱动版本 1.4.0 或更高版本。

opts 参数可用于为操作指定选项(请参阅 options.CreateCollectionOptions 文档)。

func (*Database) X删除数据库

func (d *Database) X删除数据库(上下文 context.Context) error

DropDatabase 删除数据库

func (*Database) X取数据库名称

func (d *Database) X取数据库名称() string

GetDatabaseName 返回数据库名称

func (*Database) X取集合

func (d *Database) X取集合(名称 string, 可选选项 ...*options.CollectionOptions) *Collection

Collection 从数据库获取集合

func (*Database) X执行命令

func (d *Database) X执行命令(上下文 context.Context, runCommand interface{}, 可选选项 ...options.RunCommandOptions) *mongo.SingleResult

RunCommand 执行给定的命令针对数据库。

runCommand 参数必须是要执行的命令的文档,不能为 nil。它必须是一个保持顺序的类型,如 bson.D。Map 类型如 bson.M 不是有效的。 如果命令文档包含会话 ID 或任何事务特定字段,则行为未定义。

opts 参数可用于为此次操作指定选项(请参阅 options.RunCmdOptions 文档)。

type DeleteResult

type DeleteResult struct {
	DeletedCount int64 // 删除的文档数量。
}

DeleteResult 是由 DeleteOne 和 DeleteMany 操作返回的结果类型。

type E

type E = bson.E

E 是 bson.E 的别名

type InsertManyResult

type InsertManyResult struct {
	// 插入文档的 _id 值。由驱动程序生成的值将为 primitive.ObjectID 类型。
	InsertedIDs []interface{}
}

InsertManyResult 是由 InsertMany 操作返回的一种结果类型。

type InsertOneResult

type InsertOneResult struct {
	// 插入文档的 _id。由驱动程序生成的值将为 primitive.ObjectID 类型。
	InsertedID interface{}
}

InsertOneResult 是 InsertOne 操作返回的结果类型。

type M

type M = bson.M

M 是 bson.M 的别名

type Pipeline

type Pipeline []bson.D

Pipeline 定义了聚合操作的管道

type QmgoClient

type QmgoClient struct {
	*Collection
	*Database
	*Client
}

QmgoClient 指定了操作 MongoDB 的实例

func X创建

func X创建(上下文 context.Context, 配置 *Config, 可选选项 ...options.ClientOptions) (Qmgo客户端 *QmgoClient, 错误 error)

Open creates client instance according to config QmgoClient can operates all qmgo.client 、qmgo.database and qmgo.collection

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query 结构体定义

func (*Query) X去重

func (q *Query) X去重(字段名 string, 数组指针 interface{}) error

Distinct 获取集合中指定字段的唯一值,并以切片形式返回 结果应通过指针传递给切片 该函数将验证结果切片中元素的静态类型与在mongodb中获取的数据类型是否一致 参考文献:https://docs.mongodb.com/manual/reference/command/distinct/

func (*Query) X取一条

func (q *Query) X取一条(结果指针 interface{}) error

根据过滤条件查询一条记录 若查询未找到匹配项,则返回错误

func (*Query) X取全部

func (q *Query) X取全部(结果指针 interface{}) error

根据过滤条件查询满足条件的多条记录 结果的静态类型必须是指向切片的指针

func (*Query) X取数量

func (q *Query) X取数量() (数量 int64, 错误 error)

Count 计算符合条件的条目数量

func (*Query) X取结果集

func (q *Query) X取结果集() CursorI

获取一个Cursor对象,可用于遍历查询结果集 在获取到CursorI对象后,应主动调用Close接口关闭游标

func (*Query) X取预估数量

func (q *Query) X取预估数量() (数量 int64, 错误 error)

EstimatedCount 通过使用元数据估算集合的数量

func (*Query) X字段

func (q *Query) X字段(字段Map interface{}) QueryI

Select 用于确定在返回结果中哪些字段显示或不显示 格式:bson.M{"age": 1} 表示只显示 age 字段 bson.M{"age": 0} 表示除 age 字段外的其他字段均显示 当 _id 不显示并设置为 0 时,它将被默认返回显示

func (*Query) X执行命令

func (q *Query) X执行命令(change Change, result interface{}) error

Apply runs the findAndModify command, which allows updating, replacing or removing a document matching a query and atomically returning either the old version (the default) or the new version of the document (when ReturnNew is true)

The Sort and Select query methods affect the result of Apply. In case multiple documents match the query, Sort enables selecting which document to act upon by ordering it first. Select enables retrieving only a selection of fields of the new or old document.

When Change.Replace is true, it means replace at most one document in the collection and the update parameter must be a document and cannot contain any update operators; if no objects are found and Change.Upsert is false, it will returns ErrNoDocuments. When Change.Remove is true, it means delete at most one document in the collection and returns the document as it appeared before deletion; if no objects are found, it will returns ErrNoDocuments. When both Change.Replace and Change.Remove are false,it means update at most one document in the collection and the update parameter must be a document containing update operators; if no objects are found and Change.Upsert is false, it will returns ErrNoDocuments.

reference: https://docs.mongodb.com/manual/reference/command/findAndModify/

func (*Query) X指定索引字段

func (q *Query) X指定索引字段(索引字段 interface{}) QueryI

Hint 设置Hint字段的值。 这个值应该要么是作为字符串的索引名,要么是作为文档的索引规范。 默认值为nil,这意味着不会发送任何提示。

func (*Query) X排序

func (q *Query) X排序(排序字段 ...string) QueryI

Sort 用于设置返回结果的排序规则 格式: "age" 或 "+age" 表示按年龄字段升序排序,"-age" 表示按年龄字段降序排序 当同时传入多个排序字段时,按照字段传入的顺序依次排列 例如:{"age", "-name"},首先按年龄升序排序,然后按姓名降序排序

func (*Query) X设置不超时

func (q *Query) X设置不超时(是否不超时 bool) QueryI

func (*Query) X设置批量处理数量

func (q *Query) X设置批量处理数量(数量 int64) QueryI

BatchSize 设置 BatchSize 字段的值。 表示服务器返回的每个批次中包含的最大文档数量。

func (*Query) X设置排序规则

func (q *Query) X设置排序规则(规则 *options.Collation) QueryI

func (*Query) X设置数组过滤

func (q *Query) X设置数组过滤(过滤条件 *options.ArrayFilters) QueryI

SetArrayFilter 用于应用更新数组的操作 例如: 声明一个结果变量 var res = QueryTestItem{} 定义变更内容

change := Change{
	Update:    bson.M{"$set": bson.M{"instock.$[elem].qty": 100}}, // 更新数组中符合条件的元素数量为100
	ReturnNew: false, // 是否返回更新后的文档,默认为false
}

使用cli在上下文中查找指定条件的文档(name为"Lucas") cli.Find(context.Background(), bson.M{"name": "Lucas"}). 设置数组过滤器,这里匹配"instock"数组中"warehouse"字段包含"C"或"F"的元素 .SetArrayFilters(&options.ArrayFilters{Filters: []interface{}{bson.M{"elem.warehouse": bson.M{"$in": []string{"C", "F"}}},}}). 应用上述变更到查询结果,并将更新后的内容存入res变量 .Apply(change, &res)

func (*Query) X设置最大返回数

func (q *Query) X设置最大返回数(数量 int64) QueryI

Limit 限制查询结果返回的最大文档数量为 n 默认值为 0,当设置为 0 时,表示没有限制,会返回所有匹配的结果 当 limit 值小于 0 时,负数的限制与正数类似,但会在返回单批次结果后关闭游标 参考文献:https://docs.mongodb.com/manual/reference/method/cursor.limit/index.html

func (*Query) X跳过

func (q *Query) X跳过(跳过数量 int64) QueryI

Skip skip n records

type QueryI

type QueryI interface {
	X设置排序规则(collation *options.Collation) QueryI
	X设置数组过滤(*options.ArrayFilters) QueryI
	X排序(fields ...string) QueryI
	X字段(selector interface{}) QueryI
	X跳过(n int64) QueryI
	X设置批量处理数量(n int64) QueryI
	X设置不超时(n bool) QueryI
	X设置最大返回数(n int64) QueryI
	X取一条(result interface{}) error
	X取全部(result interface{}) error
	X取数量() (n int64, err error)
	X取预估数量() (n int64, err error)
	X去重(key string, result interface{}) error
	X取结果集() CursorI
	X执行命令(change Change, result interface{}) error
	X指定索引字段(hint interface{}) QueryI
}

QueryI Query interface

type ReadPref

type ReadPref struct {
	// MaxStaleness 表示服务器被视为可选的最大过时时间。
	// 该特性从版本 3.4 开始支持。
	MaxStalenessMS int64 `json:"maxStalenessMS"`
	// 表示用户对读取操作的偏好。
	// 默认为 PrimaryMode
	Mode readpref.Mode `json:"mode"`
}

ReadPref 决定哪些服务器适合读取操作。

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session 是一个结构体,代表了 MongoDB 的逻辑会话

func (*Session) AbortTransaction

func (s *Session) AbortTransaction(ctx context.Context) error

AbortTransaction 中断当前会话的活动事务。如果当前会话没有活动事务,或者事务已被提交或中止,则此方法将返回错误。

func (*Session) EndSession

func (s *Session) EndSession(ctx context.Context)

EndSession 将终止任何现有事务并关闭会话。

func (*Session) StartTransaction

func (s *Session) StartTransaction(ctx context.Context, cb func(sessCtx context.Context) (interface{}, error), opts ...*opts.TransactionOptions) (interface{}, error)

StartTransaction starts transaction precondition: - version of mongoDB server >= v4.0 - Topology of mongoDB server is not Single At the same time, please pay attention to the following

  • make sure all operations in callback use the sessCtx as context parameter
  • Dont forget to call EndSession if session is not used anymore
  • if operations in callback takes more than(include equal) 120s, the operations will not take effect,
  • if operation in callback return qmgo.ErrTransactionRetry, the whole transaction will retry, so this transaction must be idempotent
  • if operations in callback return qmgo.ErrTransactionNotSupported,
  • If the ctx parameter already has a Session attached to it, it will be replaced by this session.

type UpdateResult

type UpdateResult struct {
	MatchedCount  int64       // 匹配过滤器的文档数量。
	ModifiedCount int64       // 此操作修改的文档数量。
	UpsertedCount int64       // 该操作执行的文档更新或插入的数量。
	UpsertedID    interface{} // _id字段是更新文档(upsert document)中的_id字段,如果未执行任何更新操作,则为nil。
}

UpdateResult 是从 UpdateOne、UpdateMany 和 ReplaceOne 操作返回的结果类型。

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL