mongodb

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2021 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Created by LonelyPale at 2019-12-06

Index

Constants

View Source
const (
	// go struct field name
	IDField         = "ID"
	CreateTimeField = "CreateTime"
	UpdateTimeField = "UpdateTime"

	// db bson field name
	IDBson         = "_id" // MongoDB ObjectID Field Name
	CreateTimeBson = "createTime"
	UpdateTimeBson = "updateTime"

	// web json field name
	IDJson         = "id"
	CreateTimeJson = "createTime"
	UpdateTimeJson = "updateTime"
)

Field Constant

View Source
const (
	ModelValueKey = "ModelValue"

	InsertOneOptionsKey = "InsertOneOptions"
	InsertOneResultKey  = "InsertOneResult"

	InsertManyOptionsKey = "InsertManyOptions"
	InsertManyResultKey  = "InsertManyResult"

	UpdateOptionsKey = "UpdateOptions"
	UpdateResultKey  = "UpdateResult"

	DeleteOptionsKey = "DeleteOptions"
	DeleteResultKey  = "DeleteResult"

	FindOneOptionsKey = "FindOneOptions"
	SingleResultKey   = "SingleResult"

	FindOptionsKey = "FindOptions"
	ResultKey      = "Result"
)
View Source
const (
	OrKey     = "$or"
	AndKey    = "$and"
	InKey     = "$in"
	NinKey    = "$nin"
	AllKey    = "$all"
	NotKey    = "$not"
	NeKey     = "$ne"  // !=
	GtKey     = "$gt"  // >
	GteKey    = "$gte" // >=
	LtKey     = "$lt"  // <
	LteKey    = "$lte" // <=
	ModKey    = "$mod" // mod 取模运算
	ExistsKey = "$exists"
	TypeKey   = "$type"
	SizeKey   = "$size"
	MatchKey  = "$elemMatch"
)

Query and Projection Operators

View Source
const (
	SetKey   = "$set"
	UnsetKey = "$unset"
	IncKey   = "$inc"
)

Field Update Operators

View Source
const (
	CreateTagName = "vCreate" //增
	UpdateTagName = "vUpdate" //改
	DeleteTagName = "vDelete" //删
	FindTagName   = "vFind"   //查
)

验证tag: 增删查改 CRUD

View Source
const DefaultTimeout = 10 * time.Second

Variables

View Source
var ErrDocumentExists = errors.New("document already exists")
View Source
var ErrDocumentNotExist = errors.New("document does not exist")
View Source
var ErrNilCollection = errors.New("collection is nil")
View Source
var ErrNilDocument = errors.New("document is nil")
View Source
var ErrNilFilter = errors.New("filter cannot be nil")
View Source
var ErrNilObjectID = errors.New("ObjectID is nil")
View Source
var ErrNilResult = errors.New("the result point cannot be nil")
View Source
var ErrNoDocuments = mongo.ErrNoDocuments
View Source
var ModelFields = model{
	ID:         "id",
	CreateTime: "createTime",
	UpdateTime: "updateTime",
}

Functions

func CloseClient added in v0.0.6

func CloseClient(client *Client) error

CloseClient 关闭 MongoDB 客户端

func IsErrIndexExists added in v0.0.8

func IsErrIndexExists(err error) bool

检查是否是触发唯一索引的错误E11000

func MakeInstance added in v0.0.4

func MakeInstance(name string) interface{}

func RegisterModel added in v0.0.8

func RegisterModel(typedNil interface{}, names ...string)

mongodb.RegisterModel((*User)(nil), UserCollectionName)

func TimeoutContext added in v0.0.4

func TimeoutContext(ts ...time.Duration) (context.Context, context.CancelFunc)

func Var added in v0.0.8

func Var(field interface{}, name string, mname string, tags ...string) error

Types

type A added in v0.0.8

type A = types.A //array

type AfterDeleter added in v0.0.4

type AfterDeleter interface {
	AfterDelete(ctx context.Context, filter interface{}, opts []*options.DeleteOptions, count int64) error
}

type AfterFinder added in v0.0.4

type AfterFinder interface {
	AfterFind(ctx context.Context, result interface{}, filter interface{}, opts interface{}) error
}

type AfterInserter added in v0.0.4

type AfterInserter interface {
	AfterInsert(ctx context.Context, documents []interface{}, opts interface{}, ids []types.ObjectID) error
}

type AfterUpdater added in v0.0.4

type AfterUpdater interface {
	AfterUpdate(ctx context.Context, filter interface{}, updater interface{}, opts []*options.UpdateOptions, result *mongo.UpdateResult) error
}

type BeforeDeleter added in v0.0.4

type BeforeDeleter interface {
	BeforeDelete(ctx context.Context, filter interface{}, opts []*options.DeleteOptions) error
}

type BeforeFinder added in v0.0.4

type BeforeFinder interface {
	BeforeFind(ctx context.Context, result interface{}, filter interface{}, opts interface{}) error
}

type BeforeInserter added in v0.0.4

type BeforeInserter interface {
	BeforeInsert(ctx context.Context, documents []interface{}, opts interface{}) error
}

type BeforeUpdater added in v0.0.4

type BeforeUpdater interface {
	BeforeUpdate(ctx context.Context, filter interface{}, updater interface{}, opts []*options.UpdateOptions) error
}

type Client

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

func Connect

func Connect(opts *ClientOptions) (*Client, error)

func GetClient added in v0.0.6

func GetClient(cfgs ...*config.MongodbConfig) *Client

func NewClient

func NewClient(opts *ClientOptions) (*Client, error)

NewClient 创建 MongoDB 客户端

func (*Client) Connect

func (c *Client) Connect(ctxs ...context.Context) error

func (*Client) DB added in v0.0.6

func (c *Client) DB(db ...string) *Database

func (*Client) Database

func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database

func (*Client) Disconnect

func (c *Client) Disconnect(ctxs ...context.Context) error

func (*Client) GetContext added in v0.0.4

func (c *Client) GetContext() (context.Context, context.CancelFunc)

func (*Client) MongoClient

func (c *Client) MongoClient() *mongo.Client

func (*Client) StartSession

func (c *Client) StartSession(opts ...*options.SessionOptions) (mongo.Session, error)

type ClientOptions

type ClientOptions struct {
	//custom options
	URI               string        //数据库连接字符串
	Timeout           time.Duration //单位秒
	EnableTransaction bool          //默认不启用事务,启用事务需要打开副本集
	DefaultDBName     string        //默认的数据库名称

	//options.ClientOptions
	MaxPoolSize uint64 //最大连接池
	MinPoolSize uint64 //最小连接池
	// contains filtered or unexported fields
}

func NewClientOptions

func NewClientOptions(uri string) *ClientOptions

func NewClientOptionsFromConfig

func NewClientOptionsFromConfig(conf *config.MongodbConfig) *ClientOptions

func NewClientOptionsFromFile added in v0.0.3

func NewClientOptionsFromFile(files ...string) *ClientOptions

func (*ClientOptions) Apply

func (c *ClientOptions) Apply()

type Collection

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

func (*Collection) Client

func (coll *Collection) Client() *Client

func (*Collection) Clone added in v0.0.4

func (coll *Collection) Clone(opts ...*CollectionOptions) (*Collection, error)

func (*Collection) Count

func (coll *Collection) Count(ctx context.Context, filter interface{}, opts ...*CountOptions) (int64, error)

func (*Collection) CreateIndex added in v0.0.8

func (coll *Collection) CreateIndex(ctx context.Context, models []mongo.IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error)

创建索引

func (*Collection) CreateUniqueIndex added in v0.0.8

func (coll *Collection) CreateUniqueIndex(keys ...string) ([]string, error)

创建唯一索引

func (*Collection) Database

func (coll *Collection) Database() *Database

func (*Collection) Delete

func (coll *Collection) Delete(ctx context.Context, filter interface{}, opts ...*DeleteOptions) (int64, error)

func (*Collection) DeleteByID added in v0.0.8

func (coll *Collection) DeleteByID(i interface{}) (int64, error)

func (*Collection) DeleteOne

func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*DeleteOptions) (int64, error)

func (*Collection) Find

func (coll *Collection) Find(ctx context.Context, result interface{}, filter interface{}, opts ...*FindOptions) error

result 必须是指向切片的指针或指向 Pager 接口的指针

func (*Collection) FindByID added in v0.0.8

func (coll *Collection) FindByID(result interface{}, i interface{}) error

func (*Collection) FindOne

func (coll *Collection) FindOne(ctx context.Context, result interface{}, filter interface{}, opts ...*FindOneOptions) error

func (*Collection) FindOneAndUpdate added in v0.0.6

func (coll *Collection) FindOneAndUpdate(ctx context.Context, result interface{}, filter interface{}, update interface{}, opts ...*FindOneAndUpdateOptions) error

func (*Collection) FindOrInsert added in v0.0.8

func (coll *Collection) FindOrInsert(ctx context.Context, filter interface{}, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)

推荐优先使用唯一索引来解决字段的唯一性问题,只有在有性能问题时才使用先查询再插入的方法 查找一条记录,如果不存在,则插入一条记录

func (*Collection) GetContext added in v0.0.4

func (coll *Collection) GetContext() (context.Context, context.CancelFunc)

func (*Collection) Insert

func (coll *Collection) Insert(ctx context.Context, documents []interface{}, opts ...*InsertManyOptions) ([]types.ObjectID, error)

func (*Collection) InsertOne

func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)

func (*Collection) MongoCollection

func (coll *Collection) MongoCollection() *mongo.Collection

func (*Collection) Name

func (coll *Collection) Name() string

func (*Collection) Save

func (coll *Collection) Save(ctx context.Context, document interface{}, opts ...*InsertOneOptions) (types.ObjectID, error)

todo: 考虑是否用 FindOneAndUpdate 替换,如用 FindOneAndUpdate 替换,则无法调用 Insert、Update callback 创建或更新一条记录

func (*Collection) Update

func (coll *Collection) Update(ctx context.Context, filter interface{}, updater interface{}, opts ...*UpdateOptions) (*mongo.UpdateResult, error)

func (*Collection) UpdateOne

func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, updater interface{}, opts ...*UpdateOptions) (*mongo.UpdateResult, error)

type CollectionOptions added in v0.0.8

type CollectionOptions = options.CollectionOptions

type CountOptions added in v0.0.8

type CountOptions = options.CountOptions

type CreateIndexesOptions added in v0.0.8

type CreateIndexesOptions = options.CreateIndexesOptions

type D added in v0.0.8

type D = types.D //

type Database

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

func (*Database) Client

func (db *Database) Client() *Client

func (*Database) Collection

func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection

func (*Database) MongoDatabase

func (db *Database) MongoDatabase() *mongo.Database

func (*Database) Name

func (db *Database) Name() string

type DeleteOptions added in v0.0.8

type DeleteOptions = options.DeleteOptions

type E added in v0.0.8

type E = types.E //

type FieldType added in v0.0.8

type FieldType interface {
	Field() string
	Bson() string
	Json() string
	ValidateTag() ValidateTag
	Kind() reflect.Kind
	Type() reflect.Type
}

type Filter added in v0.0.4

type Filter map[string]interface{}

func And added in v0.0.4

func And(values ...interface{}) Filter

func ID added in v0.0.4

func ID(value interface{}) Filter

func In added in v0.0.8

func In(key string, value interface{}) Filter

func NewFilter added in v0.0.4

func NewFilter(values ...interface{}) Filter

func NewFilterFromMap added in v0.0.8

func NewFilterFromMap(m map[string]interface{}, mtype ModelType) Filter

func Or added in v0.0.4

func Or(values ...interface{}) Filter

func (Filter) All added in v0.0.4

func (f Filter) All(key string, value interface{}) Filter

func (Filter) And added in v0.0.4

func (f Filter) And(values ...interface{}) Filter

{ $and: [ { name: { $ne: "c"} }, { name: { $ne: "go"} } ] } { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

func (Filter) Delete added in v0.0.4

func (f Filter) Delete(key string)

func (Filter) Exists added in v0.0.4

func (f Filter) Exists(key string, value bool) Filter

func (Filter) Get added in v0.0.4

func (f Filter) Get(key string) interface{}

func (Filter) Gt added in v0.0.4

func (f Filter) Gt(key string, value interface{}) Filter

func (Filter) Gte added in v0.0.4

func (f Filter) Gte(key string, value interface{}) Filter

func (Filter) ID added in v0.0.4

func (f Filter) ID(value interface{}) Filter

func (Filter) In added in v0.0.4

func (f Filter) In(key string, value interface{}) Filter

func (Filter) Lt added in v0.0.4

func (f Filter) Lt(key string, value interface{}) Filter

func (Filter) Lte added in v0.0.4

func (f Filter) Lte(key string, value interface{}) Filter

func (Filter) Ne added in v0.0.4

func (f Filter) Ne(key string, value interface{}) Filter

func (Filter) Or added in v0.0.4

func (f Filter) Or(values ...interface{}) Filter

{ $or: [ {name: "c"}, {name: "go"} ] } { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

func (Filter) Regex added in v0.0.4

func (f Filter) Regex(key string, value interface{}) Filter

模糊查询

func (Filter) RegexCondition added in v0.0.8

func (f Filter) RegexCondition(keys ...string) Filter

func (Filter) Set added in v0.0.4

func (f Filter) Set(values ...interface{}) Filter

{ name: "go" }

func (Filter) Size added in v0.0.4

func (f Filter) Size(key string, value interface{}) Filter

func (Filter) TimeCondition added in v0.0.8

func (f Filter) TimeCondition(keys ...string) Filter

func (Filter) Type added in v0.0.4

func (f Filter) Type(key string, value interface{}) Filter

type FindOneAndUpdateOptions added in v0.0.8

type FindOneAndUpdateOptions = options.FindOneAndUpdateOptions

type FindOneOptions added in v0.0.8

type FindOneOptions = options.FindOneOptions

type FindOptions added in v0.0.8

type FindOptions = options.FindOptions

type IndexModel added in v0.0.8

type IndexModel = mongo.IndexModel

type IndexOptions added in v0.0.8

type IndexOptions = options.IndexOptions

type InsertManyOptions added in v0.0.8

type InsertManyOptions = options.InsertManyOptions

type InsertOneOptions added in v0.0.8

type InsertOneOptions = options.InsertOneOptions

type M added in v0.0.8

type M = types.M //map

type Model added in v0.0.4

type Model struct {
	ID         types.ObjectID `` /* 158-byte string literal not displayed */
	CreateTime types.Time     `bson:"createTime,omitempty" json:"createTime,omitempty" validate:"omitempty" label:"创建时间"`
	UpdateTime types.Time     `bson:"updateTime,omitempty" json:"updateTime,omitempty" validate:"omitempty" label:"更新时间"`
	// contains filtered or unexported fields
}
type Service interface {
	Start() (bool, error)
	OnStart() error

	Stop() bool
	OnStop()

	Reset() (bool, error)
	OnReset() error

	IsRunning() bool

	String() string

	SetLogger(log.Logger)
}

todo: doc可优化为接口类型,如上例

func NewModel added in v0.0.4

func NewModel(doc interface{}, coll *Collection) Model

func (Model) AfterInsert added in v0.0.4

func (Model) AfterInsert(ctx context.Context, documents []interface{}, opts interface{}, ids []types.ObjectID) error

func (Model) BeforeInsert added in v0.0.4

func (Model) BeforeInsert(ctx context.Context, documents []interface{}, opts interface{}) error

func (Model) BeforeUpdate added in v0.0.4

func (Model) BeforeUpdate(ctx context.Context, filter interface{}, updater interface{}, opts []*options.UpdateOptions) error

func (Model) Collection added in v0.0.4

func (m Model) Collection() *Collection

func (Model) Create added in v0.0.8

func (m Model) Create(ctxs ...context.Context) error

Create

func (Model) Delete added in v0.0.4

func (m Model) Delete(ctxs ...context.Context) error

Delete

func (Model) Find added in v0.0.8

func (m Model) Find(ctxs ...context.Context) error

Find

func (Model) FindOrInsert added in v0.0.8

func (m Model) FindOrInsert(filter interface{}, ctxs ...context.Context) error

func (*Model) Init added in v0.0.8

func (m *Model) Init(doc interface{}, coll *Collection)

初始化文档和集合

func (Model) IsInited added in v0.0.8

func (m Model) IsInited() bool

是否已初始化

func (Model) Save added in v0.0.4

func (m Model) Save(ctxs ...context.Context) error

func (Model) Update added in v0.0.8

func (m Model) Update(ctxs ...context.Context) error

Update

func (Model) Validate added in v0.0.4

func (m Model) Validate(tags ...string) error

type ModelType added in v0.0.8

type ModelType interface {
	Field(jsonTagName string) FieldType
	Kind() reflect.Kind
	Type() reflect.Type
}

func GetModelType added in v0.0.8

func GetModelType(name string) ModelType

type ModelValidator added in v0.0.8

type ModelValidator interface {
	Validate(tags ...string) error
}

type Paginator added in v0.0.6

type Paginator interface {
	Skip() int64
	Limit() int64
	Result() interface{} //必须是切片指针
	SetTotal(n int64)
}

分页器接口 实现接口的方法必须同时是对象 (a A) 或指针 (a *A),否则断言不到此类型的接口。

type Regex added in v0.0.8

type Regex = primitive.Regex

type Sequence added in v0.0.6

type Sequence struct {
	Model `bson:"-" json:"-"`
	Key   string `bson:"key,omitempty" json:"key,omitempty" validate:"omitempty,min=1" vCreate:"required"`
	Value int64  `bson:"value,omitempty" json:"value,omitempty" validate:"omitempty,gte=1" vCreate:"required"`
	// contains filtered or unexported fields
}

func NewSequence added in v0.0.6

func NewSequence(coll *Collection) *Sequence

func (*Sequence) Inc added in v0.0.6

func (s *Sequence) Inc() (int64, error)

func (*Sequence) IncByID added in v0.0.8

func (s *Sequence) IncByID(id interface{}) (int64, error)

func (*Sequence) IncByKey added in v0.0.8

func (s *Sequence) IncByKey(key string) (int64, error)

type Sort added in v0.0.8

type Sort map[string]int

func Asc added in v0.0.8

func Asc(keys ...string) Sort

func Desc added in v0.0.8

func Desc(keys ...string) Sort

func NewSort added in v0.0.8

func NewSort(keys ...string) Sort

默认升序

func (Sort) Asc added in v0.0.8

func (s Sort) Asc(keys ...string) Sort

升序

func (Sort) Desc added in v0.0.8

func (s Sort) Desc(keys ...string) Sort

降序

type Transaction

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

func NewTransaction

func NewTransaction(client *Client) *Transaction

func (*Transaction) Commit

func (t *Transaction) Commit() error

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

func (*Transaction) Run

func (t *Transaction) Run(ctx context.Context, fn func(sctx mongo.SessionContext) error) error

自动执行事务,简化使用过程。

type UpdateOptions added in v0.0.8

type UpdateOptions = options.UpdateOptions

type Updater added in v0.0.4

type Updater map[string]interface{}

func Inc added in v0.0.6

func Inc(values ...interface{}) Updater

func NewUpdater added in v0.0.4

func NewUpdater(values ...interface{}) Updater

func Set added in v0.0.4

func Set(values ...interface{}) Updater

func Unset added in v0.0.4

func Unset(keys ...string) Updater

func (Updater) Delete added in v0.0.4

func (u Updater) Delete(key string)

func (Updater) Get added in v0.0.4

func (u Updater) Get(key string) interface{}

func (Updater) Inc added in v0.0.6

func (u Updater) Inc(values ...interface{}) Updater

{ $inc: { quantity: -2, "metrics.orders": 1 } } { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

func (Updater) Set added in v0.0.4

func (u Updater) Set(values ...interface{}) Updater

{ $set: { "details.make": "zzz" } } { $set: { "tags.1": "rain gear", "ratings.0.rating": 2 } } { $set: { <field1>: <value1>, ... } }

func (Updater) Unset added in v0.0.4

func (u Updater) Unset(keys ...string) Updater

{ $unset: { quantity: "", instock: "" } } { $unset: { <field1>: "", ... } }

func (Updater) UpdateTime added in v0.0.8

func (u Updater) UpdateTime(value interface{}) Updater

type ValidateTag added in v0.0.8

type ValidateTag interface {
	Validate() string
	Create() string
	Update() string
	Delete() string
	Find() string
	Label() string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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