mongo

package module
v1.2.8 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2023 License: Apache-2.0 Imports: 19 Imported by: 0

README

ORM使用说明

一、初始化

表定义
// 根据数据库类型定义表关系对象
var ref = mongo.NewReference()

/**
  注意:
      bson:mongo数据标签必须存在,查询使用此标签
      json:序列化json使用
      ref:外键关联方式(查询出来的数据与外键数据比较方式):
          def: 有交集即可
          all:所有的外键包含在查询出来的数据
          match:外键必须要与查询出来的数据完全匹配
*/

// 定义表结构
type Table1 struct {
// mongo 主键,bson 必须是 _id
ID   mongo.ObjectID            `bson:"_id" json:"key"`
Txt  string                    `bson:"txt" json:"txt"`
Ref  *mongo.Foreign[Table2]    `bson:"ref" json:"ref" ref:"def"`
Ref2 mongo.ForeignList[Table3] `bson:"ref2" json:"ref2" ref:"match"`
}
// 添加表定义(建议放在表声明的go文件的 init 方法中)
ref.AddTableDef("table1", dao.Table1{})

type Table2 struct {
ID   string                 `bson:"_id" json:"key"`
Name string                 `bson:"name" json:"name"`
Ref  *mongo.Foreign[Table3] `bson:"ref" json:"ref" ref:"def"`
}
ref.AddTableDef("table2", dao.Table2{})

type Table3 struct {
ID  string `bson:"_id" json:"key"`
Txt string `bson:"txt" json:"txt"`
}
ref.AddTableDef("table3", dao.Table3{})

// 编译整个数据库的表关系
ref.BuildRefs()

注:以上仅仅在项目启动执行一次,切勿在业务代码中执行调用

二、查询算子(每个算子前面需要用双下划线标注)

// 获取链接配置
opts := mongo.OptionsFromURI("mongodb://localhost:27017")
// 创建client
client, err := mongo.NewClient(context.Background(), opts)
if err != nil {
fmt.Println("get mongo client error")
panic(err)
}
// 链接数据库
db := client.Database("example")
ctx := context.Background()

// 创建表对象
tb1 := mongo.NewORMByDB(ctx, db, "table1", mongoRef)

查询有:Query Where Wheres方法,一下以 Where 为演示使用

注意:所有的 key 值,必须和 bson 一致

1、eq 等于(唯一一个可以省略的算子)

tb1.Where("key__eq", 1) or tb1.Where("key", 1)

2、ne 不等于

tb1.Where("key__ne", 1)

3、lt 小于

tb1.Where("key__lt", 1)

4、lte 小于等于

tb1.Where("key__lte", 1)

5、gt 大于

tb1.Where("key__gt", 1)

6、gte 大于等于

tb1.Where("key__gte", 1)

7、in 包含

tb1.Where("key__in", []int{1,2,3})

说明

key 可以是数组和值类型
key 与 []int{1,2,3} 存在交集即可
8、nin 不包含

tb1.Where("key__nin", []int{1,2,3})

说明

key 可以是数组和值类型
key 与 []int{1,2,3} 不存在交集
9、all 全匹配

tb1.Where("key__all", []string{"1","2","3"})

说明

key 是数组
条件当中的元素必须都在key中可以找到
10、size 数组长度判断

tb1.Where("arr__size", 1)

说明

判断数组的长度
11、exists 字段存在判断

tb1.Where("test__exists", true)

说明

判断指定的key是否存在
12、mod 取余

tb1.Where("num__mod", []int{10, 1})

说明

判断余数是否满足要求
num % 10 == 1
13、match 文档子元素判断

tb1.Where("arr__match", MixQ(map[string]interface{}{ "key": 1, "name__in": []string{"test", "test2"}, }))

说明

判断arr
元素字段
,需要满足
:
elem.id = 1 and elem.name in ["test", "test2"]
14、istartswith(startswith) 字符串开始匹配

tb1.Where("txt__istartswith", "test")

说明

判断字符串是否以给定的条件开始
`i`为`ignore`的简写
,为忽略大小写
15、iendswith(endswith) 字符串结束匹配

tb1.Where("txt__iendswith", "test")

说明

判断字符串是否以给定的条件结束
`i`为`ignore`的简写
,为忽略大小写
16、icontains(contains) 字符串包含匹配

tb1.Where("txt__icontains", "test")

说明

判断字符串是否包含给定的条件
`i`为`ignore`的简写
,为忽略大小写

注:$or $nor $and内部即可以包含基础,也可以嵌套 $or $nor $and,以下以 $or 举例

20、$or 或,其内部为基础查询,参数可以是map、[]map、[]MixQ
tb1.Where("$or", map[string]interface{}{
"key__gt": 0,
"name__startswith": "str",
})

说明

key大于0
或 name 以 "str" 开始
tb1.Where("$or", []map[string]interface{}{
{
"key__gt": 0,
"name__startswith": "str",
},{
"key__lt": 0,
"name": "string",
}
})

说明

(key大于0
且 name 以 "str" 开始
)或者
(key小于0 且 name等于"string"
)
21、 ~ 取反操作符

~ 为条件取反,必须在最前面,可用在所有前面,如果与#连用,#应在后面,如:#test

tb1.Where("~id__lt", 1)

说明

检索id不小于1的数据
22、 geo_within_polygon 闭合多边形检索

tb1.Where("geo__geo_within_polygon", [][]float64{需要一个闭合的多边形坐标集合})

说明

检索在多边形内部的数据
23、 geo_within_multi_polygon 多个闭合多边形检索

tb1.Where("geo__geo_within_multi_polygon", [][][]float64{需要多个闭合的多边形坐标集合})

说明

检索在多边形内部的数据
24、 geo_within_center_sphere 原型检索

tb1.Where("geo__geo_within_center_sphere", []float64{})

[]float64, 长度必须是3,分辨为 lng, lat, radius(米)

说明

检索原型内部的数据
25、 geo_intersects_polygon 相交判断

tb1.Where("geo__geo_intersects_polygon", [][]float64{需要一个闭合的多边形坐标集合})

说明

检索相交的数据
26、 其他geo算子
geo near query 2dsphere
    key__near: []float64 坐标点 or map[string]interface{}{
        "point": []float64 坐标点,
        "min": 最小距离,单位:米,
        "max": 最大距离,单位:米
    }
    key__near_sphere: []float64 坐标点 or map[string]interface{}{
        "point": []float64 坐标点,
        "min": 最小距离,单位:米,
        "max": 最大距离,单位:米
    }

geo within query 2d
    key__geo_within_2d_box: [][]float64, bottom left, top right
    key__geo_within_2d_polygon: [][]float64 非闭合的多边形
    key__geo_within_2d_center: []float64, 长度必须是3,分别为 lng, lat, radius(米)

三、select 查询

支持字段显示隐藏的控制

tb1.Select("txt", "-name")

-name: 隐藏name,txt或+txt: 显示txt

四、order by

tb1.Order("txt", "-name")

说明

按照txt升序
,
name降序展示数据

五、ORM 函数介绍

1、Query Where Wheres

查询条件函数

2、OverLimit(over, size uint)

配置 limit 和 offset

3、Page(pageNo, pageSize uint)

传入页码和每页的大小,框架自定转化为说明数据库的数据查询条件

4、Limit(size uint)

设置limit

5、Distinct

设置是否去重

6、Select 配置字段查询
7、Order 配置排序字段
8、ToData(result interface{}) 万能数据接收接口
其中 result 为数据指针,数据类型如下:
1、简单类型:int、string、uint等
2、简单切片:[]int []string []uint等
3、map类型:map[string]interface{}、map[string]int、map[string]string等
4、map切片:[]map[string]interface{}、[]map[string]int、[]map[string]string等
5、struct:Table1
6、struct切片:[]Table1

demo

var res []Table1
tb1.ToDate(&res)
9、PageData(result interface{}, pageNo, pageSize uint) (pg *Paging, err error) 获取某一页的数据

参数与ToData一致

type Paging struct {
PageNo    int `json:"page_no"`   //当前页
PageSize  int `json:"page_size"` //每页条数
Total     int `json:"total"`      //总条数
PageTotal int `json:"page_total"` //总页数
}
10、Exist

检查是否有数据

11、Count 获取数据条数
12、数据插入
1、InsertOne

数据类型可以是 map[string]interface{} 或 struct

2、InsertMany

参数可以是 map 与 struct 混合的数组

13、数据更新或插入
1、UpsertOne UpdateOneCustom

数据类型可以是 map[string]interface{} 或 struct

2、UpsertMany UpdateManyCustom

参数可以是 map 与 struct 混合的数组

六、事务 orm.TransSession

// 事务,要求mongo版本>4.0,需要mongo副本集群
// 返回nil事务执行成功
err = mongo.TransSession(client, func (sessionCtx mongo.SessionContext) error {
sessTb1 := mongo.NewORMByClient(sessionCtx, client, "example", "table1", mongoRef)
// 操作
//sessTb1.InsertOne()
//sessTb1.DeleteOne()
_, err = sessTb1.UpdateOne(map[string]interface{}{
"name": "test",
}, true)
if err != nil {
return err
}
return nil
})
if err != nil {
panic(err)
}

七、其他

1、mongo.Struct2Map

可以根据要求将struct转成map,过滤ref,格式化json自定义数据

八、结语

有问题随时留言,vx:lm2586127191

Documentation

Overview

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Package mongo

Index

Constants

View Source
const (
	IndexTypeAscending   = 1
	IndexTypeDescending  = -1
	IndexTypeHashed      = "hashed"
	IndexTypeText        = "text"
	IndexTypeGeo2dSphere = "2dsphere"
	IndexTypeGeo2d       = "2d"
	IndexTypeGeoHaystack = "geoHaystack"
)

所有索引类型

View Source
const (
	UpdateSet   = updateType("$set")
	UpdateUnset = updateType("$unset")
	UpdateInc   = updateType("$inc")
	UpdatePush  = updateType("$push")
	UpdatePull  = updateType("$pull")
	UpdatePop   = updateType("$pop")
)

更新类型名称

Variables

View Source
var (
	//ErrTargetNotSettable means the second param of Bind is not settable
	ErrTargetNotSettable = errors.New("[scanner]: target is not settable! a pointer is required")
)

Functions

func ObjectID2String

func ObjectID2String(v ObjectID) string

ObjectID2String object id 转 string

func ObjectIDIsZero

func ObjectIDIsZero[T objectIDType](id T) bool

func SimpleAggregate

func SimpleAggregate()

func SimpleBulkWrite

func SimpleBulkWrite()

func SimpleCount

func SimpleCount()

func SimpleCreateIndex

func SimpleCreateIndex()

func SimpleDistinct

func SimpleDistinct()

func SimpleFindDocs

func SimpleFindDocs()

func SimpleFindDocs2

func SimpleFindDocs2()

func SimpleFindOne

func SimpleFindOne()

func SimpleFindOneAndDelete

func SimpleFindOneAndDelete()

func SimpleFindOneAndReplace

func SimpleFindOneAndReplace()

func SimpleFindOneAndUpdate

func SimpleFindOneAndUpdate()

func SimpleInsertDoc

func SimpleInsertDoc()

func SimpleInsertDocs

func SimpleInsertDocs()

func SimpleMixQ

func SimpleMixQ()

func SimpleMongoNotQ

func SimpleMongoNotQ()

func SimpleMongoQ

func SimpleMongoQ()

func SimpleNewMongoQuery

func SimpleNewMongoQuery()

func SimpleNewMongoQuery2

func SimpleNewMongoQuery2()

func SimpleNewMongoQuery3

func SimpleNewMongoQuery3()

func SimpleUpdateMany

func SimpleUpdateMany()

func SimpleUpdateOne

func SimpleUpdateOne()

func Struct2Map

func Struct2Map(raw interface{}, excludeKey ...string) map[string]interface{}

func TransSession

func TransSession(cli *Client, fn func(sessionCtx SessionContext) error) error

Types

type BasicFindOptions

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

func (*BasicFindOptions) Projection

func (op *BasicFindOptions) Projection(projectionMap map[string]interface{}) *BasicFindOptions

func (*BasicFindOptions) Select

func (op *BasicFindOptions) Select(cols []string) *BasicFindOptions

Select 设置需要展示或隐藏的字段 如:["key1", "-key2"],显示key1,隐藏key2

func (*BasicFindOptions) Sort

func (op *BasicFindOptions) Sort(cols []string) *BasicFindOptions

Sort 设置排序字段 如:["key1", "-key2"],key1 升序,key2 降序

type BasicUpdateOptions

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

func (*BasicUpdateOptions) Upsert

type BulkWriteModel

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

BulkWriteModel 批量写入模型

func NewBulkWriteModel

func NewBulkWriteModel() *BulkWriteModel

NewBulkWriteModel 创建批量写入模型

func (*BulkWriteModel) AddDeleteManyModel

func (bwm *BulkWriteModel) AddDeleteManyModel(filter *Query) *BulkWriteModel

func (*BulkWriteModel) AddDeleteOneModel

func (bwm *BulkWriteModel) AddDeleteOneModel(filter *Query) *BulkWriteModel

func (*BulkWriteModel) AddInsertOneModel

func (bwm *BulkWriteModel) AddInsertOneModel(doc interface{}) *BulkWriteModel

func (*BulkWriteModel) AddNewReplaceOneModel

func (bwm *BulkWriteModel) AddNewReplaceOneModel(filter *Query, replaceDoc map[string]interface{}, upsert bool) *BulkWriteModel

func (*BulkWriteModel) AddUpdateManyCustomModel

func (bwm *BulkWriteModel) AddUpdateManyCustomModel(filter *Query, update updateType, upDoc map[string]interface{}, upsert bool) *BulkWriteModel

func (*BulkWriteModel) AddUpdateManyModel

func (bwm *BulkWriteModel) AddUpdateManyModel(filter *Query, upDoc map[string]interface{}, upsert bool) *BulkWriteModel

func (*BulkWriteModel) AddUpdateOneCustomModel

func (bwm *BulkWriteModel) AddUpdateOneCustomModel(filter *Query, update updateType, upDoc map[string]interface{}, upsert bool) *BulkWriteModel

AddUpdateOneCustomModel 自定义类型包含:

func (*BulkWriteModel) AddUpdateOneModel

func (bwm *BulkWriteModel) AddUpdateOneModel(filter *Query, upDoc map[string]interface{}, upsert bool) *BulkWriteModel

func (*BulkWriteModel) Empty

func (bwm *BulkWriteModel) Empty() bool

func (*BulkWriteModel) SetOrdered

func (bwm *BulkWriteModel) SetOrdered(ordered bool) *BulkWriteModel

type BulkWriteResult

type BulkWriteResult struct {
	// The number of documents inserted.
	InsertedCount int64

	// The number of documents matched by filters in update and replace operations.
	MatchedCount int64

	// The number of documents modified by update and replace operations.
	ModifiedCount int64

	// The number of documents deleted.
	DeletedCount int64

	// The number of documents upserted by update and replace operations.
	UpsertedCount int64

	// A map of operation index to the _id of each upserted document.
	UpsertedIDs map[int64]interface{}
}

BulkWriteResult is the result type returned by a BulkWrite operation.

type Client

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

func Connection

func Connection(ctx context.Context, appName string, mongoConf *Conf) *Client

func NewClient

func NewClient(ctx context.Context, opt *ClientOptions) (*Client, error)

func (*Client) Ctx

func (c *Client) Ctx() context.Context

func (*Client) Database

func (c *Client) Database(dbName string) *Database

func (*Client) NewSession

func (c *Client) NewSession(fn func(sessionCtx SessionContext) error) error

NewSession 要求mongo 版本 4.0起 需要mongo副本集群

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

func (*Client) TryDatabase

func (c *Client) TryDatabase(dbName string) (db *Database, exist bool, err error)

type ClientOptions

type ClientOptions struct {
	*options.ClientOptions
}

ClientOptions 客户端配置

func CreateEmptyOptions

func CreateEmptyOptions() *ClientOptions

CreateEmptyOptions 创建空的配置

func OptionsFromURI

func OptionsFromURI(uri string) *ClientOptions

OptionsFromURI 根据uri创建配置

type Collection

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

func (*Collection) Aggregate

func (c *Collection) Aggregate(ctx context.Context, results interface{}, serverMaxTime *time.Duration, pipeline ...interface{}) error

func (*Collection) BulkWrite

func (c *Collection) BulkWrite(ctx context.Context, bwm *BulkWriteModel) (*BulkWriteResult, error)

func (*Collection) Count

func (c *Collection) Count(ctx context.Context, filter *Query, opts *CountOptions) (int64, error)

func (*Collection) CreateManyIndex

func (c *Collection) CreateManyIndex(ctx context.Context, indexList []ManyIndex) error

CreateManyIndex 创建索引

func (*Collection) CreateOneIndex

func (c *Collection) CreateOneIndex(ctx context.Context, indexName string, keys []Index, indexUnique bool) error

CreateOneIndex 创建索引

func (*Collection) DeleteMany

func (c *Collection) DeleteMany(ctx context.Context, filter *Query) (*DeleteResult, error)

func (*Collection) DeleteOne

func (c *Collection) DeleteOne(ctx context.Context, filter *Query) (*DeleteResult, error)

func (*Collection) Distinct

func (c *Collection) Distinct(ctx context.Context, fieldName string,
	filter *Query, serverMaxTime *time.Duration) ([]interface{}, error)

func (*Collection) FindDocs

func (c *Collection) FindDocs(ctx context.Context,
	filter *Query, results interface{}, opts *FindOptions) error

FindDocs filter 查询对象 results slice 结果返回,可以是map or struct opts 查询参数选择

func (*Collection) FindOne

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

FindOne filter 查询对象 results 结果返回,可以是map or struct

func (*Collection) FindOneAndDelete

func (c *Collection) FindOneAndDelete(ctx context.Context,
	filter *Query, delDoc interface{}, opts *FindOneAndDelete) error

func (*Collection) FindOneAndReplace

func (c *Collection) FindOneAndReplace(ctx context.Context,
	filter *Query, newDoc map[string]interface{}, oldDoc interface{}, opts *FindOneAndReplace) error

func (*Collection) FindOneAndUpdate

func (c *Collection) FindOneAndUpdate(ctx context.Context,
	filter *Query, upDoc map[string]interface{}, oldDoc interface{}, opts *FindOneAndUpdate) error

func (*Collection) FindOneAndUpdateCustom

func (c *Collection) FindOneAndUpdateCustom(ctx context.Context,
	filter *Query, customDoc map[string]interface{}, oldDoc interface{}, opts *FindOneAndUpdate) error

func (*Collection) InsertDoc

func (c *Collection) InsertDoc(ctx context.Context, doc map[string]interface{}) (string, error)

InsertDoc 添加一个文档

func (*Collection) InsertDocs

func (c *Collection) InsertDocs(ctx context.Context, docs []interface{}, ordered bool) ([]string, error)

InsertDocs 添加数据

func (*Collection) ReplaceOne

func (c *Collection) ReplaceOne(ctx context.Context,
	filter *Query, replaceDoc map[string]interface{}, opts *Replace) (*UpdateResult, error)

func (*Collection) UpdateMany

func (c *Collection) UpdateMany(ctx context.Context,
	filter *Query, upDoc map[string]interface{}, opts *Update) (*UpdateResult, error)

func (*Collection) UpdateManyCustom

func (c *Collection) UpdateManyCustom(ctx context.Context,
	filter *Query, update updateType, updateDoc map[string]interface{}, opts *Update) (*UpdateResult, error)

func (*Collection) UpdateOne

func (c *Collection) UpdateOne(ctx context.Context,
	filter *Query, upDoc map[string]interface{}, opts *Update) (*UpdateResult, error)

func (*Collection) UpdateOneCustom

func (c *Collection) UpdateOneCustom(ctx context.Context,
	filter *Query, update updateType, updateDoc map[string]interface{}, opts *Update) (*UpdateResult, error)

type Conf

type Conf struct {
	HostMaster               string
	HostSlave                string
	ReplicaSet               string
	User                     string
	Pass                     string
	DB                       string
	AuthDB                   string
	AuthMechanism            string
	ServerSelectionTimeoutMS int
	ConnectTimeoutMS         int
	Connect                  bool
}

type CountOptions

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

func NewCount

func NewCount() *CountOptions

func (*CountOptions) Limit

func (op *CountOptions) Limit(i int64) *CountOptions

Limit 限制数据数量

func (*CountOptions) Skip

func (op *CountOptions) Skip(i int64) *CountOptions

Skip 跳过的文档数

type Database

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

func (*Database) Collection

func (db *Database) Collection(name string) *Collection

func (*Database) TryCollection

func (db *Database) TryCollection(name string) (c *Collection, exist bool, err error)

type DeleteResult

type DeleteResult struct {
	DeletedCount int64 // The number of documents deleted.
}

type FindOneAndDelete

type FindOneAndDelete struct {
	BasicFindOptions
}

func NewFindOneAndDelete

func NewFindOneAndDelete() *FindOneAndDelete

type FindOneAndReplace

type FindOneAndReplace struct {
	BasicFindOptions
	BasicUpdateOptions
}

func NewFindOneAndReplace

func NewFindOneAndReplace() *FindOneAndReplace

type FindOneAndUpdate

type FindOneAndUpdate struct {
	BasicFindOptions
	BasicUpdateOptions
}

func NewFindOneAndUpdate

func NewFindOneAndUpdate() *FindOneAndUpdate

type FindOneOptions

type FindOneOptions struct {
	BasicFindOptions
	// contains filtered or unexported fields
}

func NewFindOneOptions

func NewFindOneOptions() *FindOneOptions

NewFindOneOptions 创建新的查询选项对象

func (*FindOneOptions) Skip

func (op *FindOneOptions) Skip(i int64) *FindOneOptions

Skip 跳过的文档数

type FindOptions

type FindOptions struct {
	FindOneOptions
	// contains filtered or unexported fields
}

FindOptions 查询文档限制条件

func NewFindOptions

func NewFindOptions() *FindOptions

NewFindOptions 创建新的查询选项对象

func (*FindOptions) Limit

func (op *FindOptions) Limit(i int64) *FindOptions

Limit 限制数据数量

func (*FindOptions) Page

func (op *FindOptions) Page(no int64, size int64) *FindOptions

Page 设置分页数据

type Foreign

type Foreign[T dataType] struct {
	Ref string   `bson:"$ref" json:"ref"`
	ID  ObjectID `bson:"$id" json:"id"`
}

Foreign mongotool 外键 tag: `bson "test" json:"test" ref:"def"` ref values [def, all, match] def: 有交集即可;all:所有的外键均存在;match:所有的外键均存在,并且与条件完全一致

func ToRefData

func ToRefData[T dataType](r *Reference, data *T) (*Foreign[T], error)

func (*Foreign[T]) GetData

func (r *Foreign[T]) GetData(ctx context.Context, db *Database) (*T, error)

func (*Foreign[T]) ToData

func (r *Foreign[T]) ToData(ctx context.Context, db *Database, data interface{}) error

type ForeignList

type ForeignList[T dataType] []*Foreign[T]

ForeignList mongotool 外键数组 tag: `bson "test" json:"test" ref:"def"` ref values [def, all, match] def: 有交集即可;all:所有的外键均存在;match:所有的外键均存在,并且与条件完全一致

func ToRefListData

func ToRefListData[T dataType, DT refListType[T]](r *Reference, data DT) (ForeignList[T], error)

func (ForeignList[T]) GetData

func (r ForeignList[T]) GetData(ctx context.Context, db *Database) ([]*T, error)

func (ForeignList[T]) ToData

func (r ForeignList[T]) ToData(ctx context.Context, db *Database, data interface{}) error

type Index

type Index struct {
	Key   string
	Value interface{}
}

Index 索引数据结构

type Limit

type Limit = []uint

type ManyIndex

type ManyIndex struct {
	IndexName string
	IndexData []Index
	Unique    bool
}

ManyIndex 索引数据结构

type ORM

type ORM struct {
	Q *mongoOrmQ
	// contains filtered or unexported fields
}

func NewORMByClient

func NewORMByClient(ctx context.Context, cli *Client, dbName, tbName string, ref *Reference) *ORM

func NewORMByDB

func NewORMByDB(ctx context.Context, db *Database, tbName string, ref *Reference) *ORM

func (*ORM) BulkWrite

func (orm *ORM) BulkWrite(bwm *BulkWriteModel) (*BulkWriteResult, error)

func (*ORM) ClearCache

func (orm *ORM) ClearCache() *ORM

func (*ORM) Client

func (orm *ORM) Client() *Client

func (*ORM) Collection

func (orm *ORM) Collection() *Collection

func (*ORM) Cond

func (orm *ORM) Cond() *Query

func (*ORM) Count

func (orm *ORM) Count(clearCache bool) (int64, error)

func (*ORM) Database

func (orm *ORM) Database() *Database

func (*ORM) DeleteMany

func (orm *ORM) DeleteMany() (*DeleteResult, error)

func (*ORM) DeleteOne

func (orm *ORM) DeleteOne() (*DeleteResult, error)

func (*ORM) Distinct

func (orm *ORM) Distinct(b bool) *ORM

func (*ORM) Exist added in v1.1.0

func (orm *ORM) Exist() (bool, error)

Exist 检查数据是否存在

func (*ORM) InsertMany

func (orm *ORM) InsertMany(data []interface{}, ordered bool) ([]string, error)

func (*ORM) InsertOne

func (orm *ORM) InsertOne(data interface{}) (string, error)

func (*ORM) KeepQuery

func (orm *ORM) KeepQuery(b bool) *ORM

func (*ORM) Limit

func (orm *ORM) Limit(size uint) *ORM

func (*ORM) Order

func (orm *ORM) Order(cols ...string) *ORM

func (*ORM) OverLimit

func (orm *ORM) OverLimit(over, size uint) *ORM

func (*ORM) Page

func (orm *ORM) Page(pageNo, pageSize uint) *ORM

func (*ORM) PageData

func (orm *ORM) PageData(target interface{}, pageNo, pageSize uint) (*Paging, error)

func (*ORM) Projection

func (orm *ORM) Projection(col string, value interface{}) *ORM

func (*ORM) Projections

func (orm *ORM) Projections(where Where) *ORM

func (*ORM) Query

func (orm *ORM) Query(pair ...interface{}) *ORM

Query 条件对 "id__gt", 1, "name": "test"

func (*ORM) ReplaceOne

func (orm *ORM) ReplaceOne(data map[string]interface{}, upsert bool) (*UpdateResult, error)

func (*ORM) Select

func (orm *ORM) Select(cols ...string) *ORM

func (*ORM) ToData

func (orm *ORM) ToData(target interface{}) (err error)

func (*ORM) ToJSON

func (orm *ORM) ToJSON() string

func (*ORM) UpdateMany

func (orm *ORM) UpdateMany(data map[string]interface{}, upsert bool) (*UpdateResult, error)

func (*ORM) UpdateManyCustom

func (orm *ORM) UpdateManyCustom(update updateType, data map[string]interface{}, upsert bool) (*UpdateResult, error)

func (*ORM) UpdateOne

func (orm *ORM) UpdateOne(data map[string]interface{}, upsert bool) (*UpdateResult, error)

func (*ORM) UpdateOneCustom

func (orm *ORM) UpdateOneCustom(update updateType, data map[string]interface{}, upsert bool) (*UpdateResult, error)

func (*ORM) Where

func (orm *ORM) Where(col string, value interface{}) *ORM

func (*ORM) Wheres

func (orm *ORM) Wheres(where Where) *ORM

type ObjectID

type ObjectID = primitive.ObjectID

func NewObjectID

func NewObjectID() ObjectID

NewObjectID 生成ObjectID

func String2ObjectID

func String2ObjectID(v string) (hex ObjectID, err error)

String2ObjectID string 转 object id

func TryString2ObjectID

func TryString2ObjectID(v string) ObjectID

type Order

type Order = []string

type Paging

type Paging struct {
	PageNo    int `json:"page_no"`    //当前页
	PageSize  int `json:"page_size"`  //每页条数
	Total     int `json:"total"`      //总条数
	PageTotal int `json:"page_total"` //总页数
}

type Projection

type Projection = map[string]interface{}

type Query

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

Query = : "key": "val" or "key__eq": "val" < : "key__lt": 1 <= : "key__lte": 1 > : "key__gt": 1 >= : "key__gte": 1 != : "key__ne": 1 in : "key__in": [1] all : "key__all": [1, 2, 3] not in : "key__nin": [1] size : "arr__size": 1 exists : "key__exists": true mod : "key__mod": [10, 1], 基数,余数 elemMatch : "key__match": MongoQuery like :

"key__istartswith": "123"
"key__startswith": "123"
"key__iendswith": "123"
"key__endswith": "123"
"key__icontains": "123"
"key__contains": "123"

geo within query 2dsphere

key__geo_within_polygon: [][]float64 or [][][]float64 闭合的多边形
key__geo_within_multi_polygon: [][][]float64 or [][][][]float64 多个闭合的多边形
key__geo_within_center_sphere: []float64, 长度必须是3,分辨为 lng, lat, radius(米)

geo intersects query 2dsphere

key__geo_intersects_polygon: [][]float64 or [][][]float64 闭合的多边形

geo near query 2dsphere

		key__near: []float64 坐标点 or map[string]interface{}{
			"point": []float64 坐标点,
            "min": 最小距离,单位:米,
            "max": 最大距离,单位:米
		}
		key__near_sphere: []float64 坐标点 or map[string]interface{}{
			"point": []float64 坐标点,
            "min": 最小距离,单位:米,
            "max": 最大距离,单位:米
		}

geo within query 2d

key__geo_within_2d_box: [][]float64, bottom left, top right
key__geo_within_2d_polygon: [][]float64 非闭合的多边形
key__geo_within_2d_center: []float64, 长度必须是3,分辨为 lng, lat, radius(米)

func MixQ

func MixQ(cond map[string]interface{}) *Query

MixQ ~: 结果取反,其中:$and、$or、$nor不适应 $and、$or、$nor: values type must be map[string]interface{} or []*MongoQuery or []interface or []map[string]interface{}

func NewAnd

func NewAnd(filter ...*Query) *Query

func NewNor

func NewNor(filter ...*Query) *Query

func NewOr

func NewOr(filter ...*Query) *Query

func NewQuery

func NewQuery() *Query

func NotQ

func NotQ(key string, value interface{}) *Query

func Q

func Q(key string, value interface{}) *Query

func (*Query) And

func (q *Query) And(filter ...*Query) *Query

func (*Query) Cond

func (q *Query) Cond() map[string]interface{}

func (*Query) Empty

func (q *Query) Empty() bool

func (*Query) JSON

func (q *Query) JSON() string

func (*Query) Nor

func (q *Query) Nor(filter ...*Query) *Query

func (*Query) Or

func (q *Query) Or(filter ...*Query) *Query

func (*Query) SetRawCond

func (q *Query) SetRawCond(cond map[string]interface{}) *Query

SetRawCond cond default nil means is not HQL and cond is not nil means use MongoQuery cond nil close raw query

type RefWhere

type RefWhere = map[string]interface{}

type Reference

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

Reference 表定义

func NewReference

func NewReference() *Reference

func (*Reference) AddTableDef

func (r *Reference) AddTableDef(tbName string, def interface{})

func (*Reference) BuildRefs

func (r *Reference) BuildRefs()

type Replace

type Replace struct {
	BasicUpdateOptions
}

func NewReplace

func NewReplace() *Replace

type Select

type Select = []string

type SessionContext

type SessionContext = mongo.SessionContext

type Update

type Update struct {
	BasicUpdateOptions
}

func NewUpdate

func NewUpdate() *Update

type UpdateResult

type UpdateResult struct {
	MatchedCount  int64       // The number of documents matched by the filter.
	ModifiedCount int64       // The number of documents modified by the operation.
	UpsertedCount int64       // The number of documents upserted by the operation.
	UpsertedID    interface{} // The _id field of the upserted document, or nil if no upsert was done.
}

type Where

type Where = map[string]interface{}

Directories

Path Synopsis
dao

Jump to

Keyboard shortcuts

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