mgoc

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2023 License: MIT Imports: 30 Imported by: 0

README

MongoDB ORM client - mgoc

部署MongoDB

  • 启动容器

# start mongodb by docker
$ docker run -p 27017:27017 --restart always -v /data/mongodb/db:/data/db --name mongodb -d mongo:4.4.10
  • 创建登录账号

账户: root 密码: 123456

$ docker exec -it mongodb mongo admin
> use admin
> db.createUser({user:"root", pwd: "123456", roles: ["root"]})
> exit

导入测试数据

  • 进入容器终端
$ docker exec -it mongodb bash
# 在容器内安装wget
root@072bedc2e6c5:/# apt-get update && apt-get install wget
root@072bedc2e6c5:/# cd /tmp
root@072bedc2e6c5:/tmp# 
  • 基于经纬度的测试数据

restaurants.json是餐馆所在经纬度数据

https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/restaurants.json

# 下载保存到/tmp目录
root@072bedc2e6c5:/tmp# wget https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/restaurants.json
  • 基于GeoJSON的测试数据

neighborhoods.json数据是一些多边形范围数据(由N个点围成一圈)

https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/neighborhoods.json

# 下载保存到/tmp目录
root@072bedc2e6c5:/tmp# wget https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/neighborhoods.json
  • 导入测试数据到test库
root@072bedc2e6c5:/tmp# ls *.json
neighborhoods.json  restaurants.json

root@072bedc2e6c5:/tmp# mongoimport restaurants.json -c restaurants 
2023-05-10T09:20:32.821+0000    connected to: mongodb://localhost/
2023-05-10T09:20:35.517+0000    25359 document(s) imported successfully. 0 document(s) failed to import.

root@072bedc2e6c5:/tmp# mongoimport neighborhoods.json -c neighborhoods
2023-05-10T09:21:05.400+0000    connected to: mongodb://localhost/
2023-05-10T09:21:07.305+0000    195 document(s) imported successfully. 0 document(s) failed to import.
  • 登录mongo终端创建索引
root@072bedc2e6c5:/tmp# mongo

# 切换到test库
> use test
# 查询一条数据看看表结构
> db.restaurants.find().limit(1).pretty()
{
        "_id" : ObjectId("55cba2476c522cafdb053ae2"),
        "location" : {
                "coordinates" : [
                        -73.98513559999999,
                        40.7676919
                ],
                "type" : "Point"
        },
        "name" : "Dj Reynolds Pub And Restaurant"
}
# 为restaurants表location字段创建2D球面索引
> db.restaurants.createIndex({"location":"2dsphere"})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
# 为neighborhoods表geometry字段建立2D球面索引
> db.neighborhoods.createIndex({ geometry: "2dsphere" })
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

快速开始

  • 所有的ORM操作必须是以Model方法开始,参数除执行delete/update操作之外都是必填
  • Table方法通常情况下也是必须调用的方法(除了数据库层面的聚合操作)
package main
import (
    "time"
    "github.com/civet148/log"
    "github.com/civet148/mgoc"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Student struct {
      Id          string            `bson:"_id,omitempty"`
      Name        string            `bson:"name"`
      Sex         string            `bson:"sex"`
      Age         int               `bson:"age"`
      Balance     mgoc.Decimal      `bson:"balance"`
      ClassNo     string            `bson:"class_no"`
      CreatedTime time.Time         `bson:"created_time"`
}

func main() {
	e, err := mgoc.NewEngine("mongodb://root:123456@127.0.0.1:27017/test?authSource=admin")
	if err != nil {
		log.Errorf(err.Error())
		return
	}
	var students []*Student
	err = e.Model(&students).
            Table("student_info").
            Options(&options.FindOptions{}).
            Desc("created_time").
            Limit(10).
            Query()
	if err != nil {
		log.Errorf(err.Error())
		return
	}
	for _, s := range students {
		log.Infof("student %+v", s)
	}
}

选项

  • Options方法 [optional]

    根据实际操作类型不同可输入不同的Option类型,比如查询时选填options.FindOptions,更新时可选填options.UpdateOptions 插入单条记录时可选填options.InsertOneOptions,插入多条则是options.InsertManyOptions等等(选填)

插入操作

  • 单条插入
var student = Student{
		Name:        "john",
		Sex:         "male",
		Age:         13,
		ClassNo:     "CLASS-3",
		Balance:     mgoc.NewDecimal("532.324"),
		CreatedTime: time.Now(),
	}
ids, err := e.Model(&student).
		Table("student_info").
		Options(&options.InsertOneOptions{}).
		Insert()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("[Single] insert id %+v", ids)
  • 多条插入(非事务)
var students = []*Student{
		{
			Name:        "lory",
			Sex:         "male",
			Age:         14,
			ClassNo:     "CLASS-1",
			CreatedTime: time.Now(),
		},
		{
			Name:        "katy",
			Sex:         "female",
			Age:         15,
			ClassNo:     "CLASS-2",
			CreatedTime: time.Now(),
		},
	}
ids, err := e.Model(&students).
		Options(&options.InsertManyOptions{}).
		Table("student_info").
		Insert()
if err != nil {
    log.Errorf(err.Error())
    return 
}
log.Infof("[Many] insert ids %+v", ids)

查询操作

  • 单条查询

SELECT * FROM student_info LIMIT 1

var err error
var student *Student
err = e.Model(&student).
        Table("student_info").
        Limit(1).
        Query()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("single student %+v", student)
  • 多条查询

SELECT _id, name, age, sex FROM student_info ORDER BY created_time DESC LIMIT 10

var err error
var students []*Student
err = e.Model(&students).
        Table("student_info").
        Select("_id", "name", "age", "sex").
        Options(&options.FindOptions{}).
        Desc("created_time").
        Limit(10).
        Query()
if err != nil {
    log.Errorf(err.Error())
    return
}
for _, student := range students {
    log.Infof("student %+v", student)
}
  • 分页查询

SELECT _id, name, age, sex FROM student_info ORDER BY created_time DESC LIMIT 0,10

var students []*Student
total, err := e.Model(&students).
        Table("student_info").
        Select("_id", "name", "age", "sex").
        Options(&options.FindOptions{}).
        Desc("created_time").
        Page(0, 10). //Page(2, 10) == LIMIT 2*10, 10
        QueryEx()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("student total %+v", total)
for _, student := range students {
    log.Infof("student %+v", student)
}
  • 条件查询

SELECT _id, name, age, sex FROM student_info WHERE class_no='CLASS-2' AND age >= 11 and age <=16 ORDER BY created_time DESC

var err error
var students []*Student
err = e.Model(&students).
        Table("student_info").
        Select("_id", "name", "age", "sex").
        Options(&options.FindOptions{}).
        Eq("class_no", "CLASS-2").
        Gte("age", 11).
        Lte("age", 16).
        Desc("created_time").
        Query()
if err != nil {
    log.Errorf(err.Error())
    return
}
for _, student := range students {
    log.Infof("student %+v", student)
}
  • 自定义查询

SELECT _id, name, age, sex FROM student_info WHERE class_no='CLASS-2' AND age >= 11 and age <=16 ORDER BY created_time DESC

var err error
var students []*Student
err = e.Model(&students).
        Table("student_info").
        Select("_id", "name", "age", "sex").
        Options(&options.FindOptions{}).
        Filter(bson.M{
            "class_no":"CLASS-2",
            "age": bson.M{"$gte":11},
            "age": bson.M{"$lte":16},
        }).
        Desc("created_time").
        Query()
if err != nil {
    log.Errorf(err.Error())
    return
}
for _, student := range students {
    log.Infof("student %+v", student)
}

更新操作

  • 通过数据模型更新字段

UPDATE student_info SET name='kary', sex='female', age=39, balance='123.456', created_time=NOW() WHERE _id='6438f32fd71fc42e601558aa'

// 更新Id值6438f32fd71fc42e601558aa对应的数据记录
var student = &Student{
		Id:          mgoc.MakeObjectID("6438f32fd71fc42e601558aa").(mgoc.ObjectID),
		Name:        "kary",
		Sex:         "female",
		Age:         39,
		Balance:     mgoc.NewDecimal("123.456"),
		CreatedTime: time.Now(),
	}
_, err := e.Model(&student).
            Table("student_info").
            Options(&options.UpdateOptions{}).
            Select("name", "sex", "age", "balance", "created_time").
            Update()
if err != nil {
    log.Errorf(err.Error())
    return
}
  • 通过Set方式更新字段
_, err := e.Model().
            Table("student_info").
            Options(&options.UpdateOptions{}).
            Id("6438f32fd71fc42e601558aa").
            Set("name", "mason").
            Set("sex", "male").
            Set("balance", mgoc.NewDecimal("123.456")).
            Update()
if err != nil {
    log.Errorf(err.Error())
    return
}
  • 结构嵌套更新
type ExtraData struct {
    IdCard      string   `bson:"id_card"`
    Address     string   `bson:"address"`
}

type Student struct {
    Id          string          `bson:"_id,omitempty"`
    Name        string          `bson:"name"`
    Sex         string          `bson:"sex"`
    Age         int             `bson:"age"`
    ClassNo     string          `bson:"class_no"`
    Balance     mgoc.Decimal    `bson:"balance"`
    CreatedTime time.Time       `bson:"created_time"`
    ExtraData   ExtraData       `bson:"extra_data"`
}
oid, err := mgoc.NewObjectIDFromString("6438f32fd71fc42e601558aa")
if err != nil {
    log.Errorf(err.Error())
    return
}
var student = &Student{
        Id:          oid,
        ClassNo:     "CLASS-3",
        ExtraData:   ExtraData {
            IdCard: "6553239109322",
        },
    }
// UPDATE student_info 
// SET class_no='CLASS-3', extra_data.id_card='6553239109322'
// WHERE _id='6438f32fd71fc42e601558aa'
_, err = e.Model(&student).
            Table("student_info").
            Options(&options.UpdateOptions{}).
            Select("class_no", "extra_data.id_card").
            Update()
if err != nil {
    log.Errorf(err.Error())
    return
}

//等同于下面的方式
_, err = e.Model().
            Table("student_info").
            Id("6438f32fd71fc42e601558aa").
            Options(&options.UpdateOptions{}).
            Set("class_no", "CLASS-3").
            Set("extra_data.id_card", "6553239109322").
            Update()
if err != nil {
    log.Errorf(err.Error())
    return
}

更新或插入

var err error
_, err = e.Model().
        Table("student_info").
        Id("6438f32fd71fc42e601558aa").
        Set("name", "rose").
        Set("sex", "female").
        Set("age", 18).
        Set("created_time", time.Now()).
        Set("balance", mgoc.NewDecimal("520.1314")).
        Upsert()
if err != nil {
    log.Errorf(err.Error())
    return
}

//使用数据模型进行upsert操作(如果已id对应数据存在则更新balance)
oid, err := mgoc.NewObjectIDFromString("6438f32fd71fc42e601558aa")
if err != nil {
  log.Errorf(err.Error())
  return
}
var student = &docStudent{
    Id:          oid,
    Name:        "rose",
    Sex:         "female",
    Age:         18,
    Balance:     NewDecimal("123.456"),
    CreatedTime: time.Now(),
}
_, err = e.Model(&student).
          Table(TableNameStudentInfo).
          Select("balance").
          Upsert()
if err != nil {
  log.Errorf(err.Error())
  return
}

删除操作

rows, err := e.Model().
                Table("student_info").
                Options(&options.DeleteOptions{}).
                Id("6438f32fd71fc42e601558aa").
                Delete()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("rows %d deleted", rows)

聚合查询

  • ORM聚合查询

SELECT AVG(age) AS age, SUM(1) AS total, SUM(balance) as balance FROM student_info WHERE sex='female' GROUP BY name, age

/*
	db.getCollection("student_info").aggregate([
        {
            "$match":{
                "sex":"female"
            },
        },
        {
            "$group":{
                        "_id":{"name":"$name", "age":"$age"},
                        "age":{ "$avg":"$age"},
                        "balance":{ "$sum":"$balance"},
                        "total":{ "$sum":1}
            }
        }
    ])
----------------------------------------------------------------------
{
    "_id": {
        "name": "katy3",
        "age": NumberInt("28")
    },
    "age": 28,
    "balance": NumberDecimal("24149.3374"),
    "total": 8
}
// 2
{
    "_id": {
        "name": "katy3",
        "age": NumberInt("27")
    },
    "age": 27,
    "balance": NumberDecimal("234"),
    "total": 1
}
// 3
{
    "_id": {
        "name": "rose",
        "age": NumberInt("18")
    },
    "age": 18,
    "balance": NumberDecimal("520.1314"),
    "total": 1
}
*/
  type AggID struct {
      Name string `bson:"name"`
  }
  type StudentAgg struct {
    ID    AggID             `bson:"_id"`
    Age   float64           `bson:"age"`
    Total int               `bson:"total"`
    Balance mgoc.Decimal    `bson:"balance"`
  }
  var agg []*StudentAgg
  err := e.Model(&agg).
        Table("student_info").
        Avg("age").
        Sum("total", 1).
        Sum("balance").
        Eq("sex", "female").
        GroupBy("name", "age").
        Aggregate()
  if err != nil {
    log.Errorf(err.Error())
    return
  }
  log.Infof("aggregate rows %d", len(agg))
  for _, a := range agg {
    log.Infof("%+v", a)
  }
  • 自定义聚合查询

SELECT AVG(age) AS age, COUNT(1) AS total FROM student_info WHERE sex='female'

/*
		db.getCollection("student_info").aggregate([
		   {
		     "$match":{
				    "sex":"female"
			   },
			 },
			 {
			   "$group":{
			      		"_id":null,
						"age":{ "$avg":"$age"},
						"total":{ "$sum":1}
					}
		   },
			 {
			   "$project":{
			         "_id":0,
					 "age":1,
					 "total":1
					}
			 }
		]
		)
		----------
		{
		    "age": 18,
		    "total": 14
		}
*/

type StudentAgg struct {
  Age   float64 `bson:"age"`
  Total int     `bson:"total"`
}
var agg []*StudentAgg
// create match stage
match := bson.D{
    {
        "$match", bson.D{
            {"sex", "female"},
        },
    },
}
// create group stage
group := bson.D{
    {"$group", bson.D{
        {"_id", nil},
        {"age", bson.D{{"$avg", "$age"}}},
        {"total", bson.D{{"$sum", 1}}},
    }}}
// create projection stage
project := bson.D{
    {"$project", bson.D{
        {"_id", 0},
        {"age", 1},
        {"total", 1},
    }}}
err := e.Model(&agg).
        Table("student_info").
        Options(&options.AggregateOptions{}).
        Pipeline(match, group, project).
        Aggregate()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("aggregate rows %d", len(agg))
for _, a := range agg {
    log.Infof("%+v", a)
}

地理位置查询

  • 查询某一点1000米范围内所有的餐馆
type Restaurant struct {
	Id       string `json:"_id" bson:"_id,omitempty"`
	Location struct {
		Type        string    `json:"type" bson:"type"`
		Coordinates []float64 `json:"coordinates" bson:"coordinates"`
	} `json:"location" bson:"location"`
	Name     string  `json:"name" bson:"name"`
	Distance float64 `json:"distance" bson:"distance"`
}
	
const maxMeters = 1000 //meters
var pos = mgoc.Coordinate{X: -73.93414657, Y: 40.82302903}
//query restaurants near by distance 1000 meters
var restaurants []*Restaurant
err := e.Model(&restaurants).
        Table("restaurants").
        GeoCenterSphere("location", pos, maxMeters).
        Query()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("center sphere restaurants total [%d]", len(restaurants))
  • 查询某个社区范围内的所有餐馆
type Neighborhood struct {
	Id       string   `json:"_id" bson:"_id,omitempty"`
	Geometry mgoc.Geometry `json:"geometry" bson:"geometry"`
	Name     string   `json:"name" bson:"name"`
}
type Restaurant struct {
	Id       string `json:"_id" bson:"_id,omitempty"`
	Location struct {
		Type        string    `json:"type" bson:"type"`
		Coordinates []float64 `json:"coordinates" bson:"coordinates"`
	} `json:"location" bson:"location"`
	Name     string  `json:"name" bson:"name"`
	Distance float64 `json:"distance" bson:"distance"`
}

var neighbor *Neighborhood
var pos = Coordinate{X: -73.93414657, Y: 40.82302903}
//查询 -73.93414657, 40.82302903 所在社区的社区范围信息
err = e.Model(&neighbor).
        Table("neighborhoods").
        Filter(bson.M{
            "geometry": bson.M{
                mgoc.KeyGeoIntersects: bson.M{
                    mgoc.KeyGeoMetry: mgoc.NewGeoMetry(mgoc.GeoTypePoint, mgoc.FloatArray{pos.X, pos.Y}),
                },
            },
        }).
        Limit(1).
        Query()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("neighborhood [%+v]", neighbor)
//查询社区范围内的餐馆
var restaurants []*Restaurant
err = e.Model(&restaurants).
        Table("restaurants").
        Geometry("location", &neighbor.Geometry).
        Query()
if err != nil {
    log.Errorf(err.Error())
    return
}
log.Infof("neighborhood restaurants total [%d]", len(restaurants))
  • 查询某一点附近1000米内的所有餐馆数据并附带距离
type Restaurant struct {
	Id       string `json:"_id" bson:"_id,omitempty"`
	Location struct {
		Type        string    `json:"type" bson:"type"`
		Coordinates []float64 `json:"coordinates" bson:"coordinates"`
	} `json:"location" bson:"location"`
	Name     string  `json:"name" bson:"name"`
	Distance float64 `json:"distance" bson:"distance"`
}
const maxMeters = 1000 //meters
var pos = Coordinate{X: -73.93414657, Y: 40.82302903}
var restaurants []*Restaurant
err := e.Model(&restaurants).
        Table("restaurants").
        Limit(10).
        Asc("distance").
        GeoNearByPoint(
            "location", //存储经纬度的字段
            pos, //当前位置数据
            maxMeters, //最大距离数(米)
            "distance"). //距离数据输出字段名
        Aggregate()
if err != nil {
    log.Errorf(err.Error())
    return 
}
for _, restaurant := range restaurants {
    log.Debugf("geo near restaurant [%+v]", restaurant)
}
log.Infof("geo near restaurants total [%d]", len(restaurants))

切换数据库

  db := e.Use("test2")

部分ORM方法说明

FindOne

查找一条记录

UpdateOne

只更新一条记录

FindOneUpdate

查找一条记录并更新

FindOneReplace

查找一条记录并替换

FindOneDelete

查找一条记录并删除

Pipeline(args...)

流水线方法,当使用该方法时会忽略ORM的其他聚合操作(GroupBy/Sum/Avg/Min/Max...)

Page(no, size)

分页查询,仅QueryEx执行有效. Page(0,10) == LIMIT 0, 10 Page(1,10) == LIMIT 1*10, 10

Ne("field", value)

等价于 {"field":{"$ne":value}}

Eq/Equal("field", value)

等价于 {"field":{"$eq":value}}

Gt("field", value)

等价于 {"field":{"$gt":value}}

Gte("field", value)

等价于 {"field":{"$gte":value}}

Lt("field", value)

等价于 {"field":{"$lt":value}}

Lte("field", value)

等价于 {"field":{"$lte":value}}

GtLt("field", value1, value2)

等价于 {"field":{"$gt":value1, "$lt":value2}}

GteLt("field", value1, value2)

等价于 {"field":{"$gte":value1, "$lt":value2}}

GteLte("field", value1, value2)

等价于 {"field":{"$gte":value1, "$lte":value2}}

GtLte("field", value1, value2)

等价于 {"field":{"$gt":value1, "$lte":value2}}

Sum("field", values...)

聚合操作求和, 针对filed做聚合时values可不填,同时values可以是数字也可以是bson.M对象 指定字段时Sum("field") 等价于 {"field":{"$sum":"$field"}} 指定计数时Sum("field", 1) 等价于 {"field":{"$sum":1}}

Avg("field", values...)

聚合操作求平均值, 针对filed做聚合时values可不填,同时values也可以是bson.M对象 指定字段时Avg("field") 等价于 {"field":{"$avg":"$field"}}

Max("field", values...)

聚合操作取最大值, 针对filed做聚合时values可不填,同时values也可以是bson.M对象 指定字段时Max("field") 等价于 {"field":{"$max":"$field"}}

Min("field", values...)

聚合操作取最小值, 针对filed做聚合时values可不填,同时values也可以是bson.M对象 指定字段时Min("field") 等价于 {"field":{"$min":"$field"}}

Documentation

Index

Constants

View Source
const (
	KeyIn               = "$in"
	KeyEqual            = "$eq"
	KeyAnd              = "$and"
	KeyOr               = "$or"
	KeyGreaterThan      = "$gt"
	KeyGreaterThanEqual = "$gte"
	KeyLessThan         = "$lt"
	KeyLessThanEqual    = "$lte"
	KeyNotEqual         = "$ne"
	KeyExists           = "$exists"
	KeyRegex            = "$regex"
	KeySet              = "$set"
	KeyElemMatch        = "$elemMatch"
	KeyMatch            = "$match"
	KeyGroup            = "$group"
	KeyHaving           = "$having"
	KeyProject          = "$project"
	KeySort             = "$sort"
	KeySkip             = "$skip"
	KeyLimit            = "$limit"
	KeySum              = "$sum"
	KeyAll              = "$all"
	KeyNear             = "$near"
	KeyGeoNear          = "$geoNear"
	KeyGeoWithin        = "$geoWithin"
	KeyCenter           = "$center"
	KeyCenterSphere     = "$centerSphere"
	KeyGeoIntersects    = "$geoIntersects"
	KeyNearSphere       = "$nearSphere"
	KeyGeoMetry         = "$geometry"
	KeyMaxDistance      = "$maxDistance"
	KeyMax              = "$max"
	KeyMin              = "$min"
	KeyAvg              = "$avg"
	KeyMod              = "$mod"
	KeyAbs              = "$abs"
	KeyUnwind           = "$unwind"
	KeyRound            = "$round"
)
View Source
const (
	ModelType_Struct   = 1
	ModelType_Slice    = 2
	ModelType_Map      = 3
	ModelType_BaseType = 4
)
View Source
const (
	TAG_VALUE_NULL   = ""
	TAG_VALUE_IGNORE = "-" //ignore
)
View Source
const (
	URL_SCHEME_SEP    = "://"
	URL_QUERY_SLAVE   = "slave"
	URL_QUERY_MAX     = "max"
	URL_QUERY_IDLE    = "idle"
	URL_QUERY_CHARSET = "charset"
)
View Source
const (
	OfficalObjectIdSize = 24
	MgoV2ObjectIdSize   = 48
)
View Source
const (
	TAG_NAME_BSON = "bson"
)

Variables

This section is empty.

Functions

func All added in v0.6.0

func All(expr interface{}) bson.M

func ContextWithTimeout

func ContextWithTimeout(timeoutSeconds int) (context.Context, context.CancelFunc)

func ConvertValue added in v0.5.0

func ConvertValue(column string, value interface{}) (v interface{})

func MakeObjectID added in v1.0.0

func MakeObjectID(v interface{}) (id interface{})

func Radian added in v0.6.0

func Radian(meters uint64) float64

计算弧度

func RoundColumn added in v1.2.0

func RoundColumn(strColumn string, place int) bson.M

func Str2ObjectID added in v0.5.0

func Str2ObjectID(strId string) (id interface{})

func Sum added in v0.5.4

func Sum(expr interface{}) bson.M

func ToBool added in v0.5.4

func ToBool(expr interface{}) bson.M

func ToDate added in v0.5.4

func ToDate(expr interface{}) bson.M

func ToDecimal added in v0.5.4

func ToDecimal(expr interface{}) bson.M

func ToDouble added in v0.5.4

func ToDouble(expr interface{}) bson.M

func ToInt added in v0.5.4

func ToInt(expr interface{}) bson.M

func ToLong added in v0.5.4

func ToLong(expr interface{}) bson.M

func ToLower added in v0.5.4

func ToLower(expr interface{}) bson.M

func ToObjectId added in v0.5.4

func ToObjectId(expr interface{}) bson.M

func ToString added in v0.5.4

func ToString(expr interface{}) bson.M

func ToUpper added in v0.5.4

func ToUpper(expr interface{}) bson.M

Types

type Coordinate added in v0.6.0

type Coordinate struct {
	X float64 `json:"x" bson:"x"`
	Y float64 `json:"y" bson:"y"`
}

type DateTime added in v0.7.2

type DateTime = primitive.DateTime

func NewDateTimeFromTime added in v0.7.2

func NewDateTimeFromTime(t time.Time) DateTime

type Decimal

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

func NewDecimal

func NewDecimal(v interface{}) (d Decimal)

func (Decimal) Abs

func (d Decimal) Abs() Decimal

Abs returns the absolute value of the decimal.

func (Decimal) Add

func (d Decimal) Add(d2 interface{}) Decimal

Add returns d + d2

func (Decimal) Amount2Btc

func (d Decimal) Amount2Btc() Decimal

func (Decimal) Amount2Coin

func (d Decimal) Amount2Coin(prec int) Decimal

func (Decimal) Amount2Ether

func (d Decimal) Amount2Ether() Decimal

func (Decimal) Amount2FIL

func (d Decimal) Amount2FIL() Decimal

func (Decimal) BigInt

func (d Decimal) BigInt() (b *big.Int, ok bool)

func (Decimal) Btc2Amount

func (d Decimal) Btc2Amount() Decimal

func (Decimal) Cmp

func (d Decimal) Cmp(d2 interface{}) int

Cmp compares the numbers represented by d and d2 and returns:

-1 if d <  d2
 0 if d == d2
+1 if d >  d2

func (Decimal) Coin2Amount

func (d Decimal) Coin2Amount(prec int) Decimal

func (Decimal) Cos

func (d Decimal) Cos() Decimal

Cos returns the cosine of the radian argument x.

func (Decimal) Div

func (d Decimal) Div(d2 interface{}) Decimal

Div returns d / d2. If it doesn't divide exactly, the result will have DivisionPrecision digits after the decimal point.

func (Decimal) Equal

func (d Decimal) Equal(d2 interface{}) bool

Equal returns whether the numbers represented by d and d2 are equal.

func (Decimal) Ether2Amount

func (d Decimal) Ether2Amount() Decimal

func (Decimal) FIL2Amount

func (d Decimal) FIL2Amount() Decimal

func (Decimal) Float64

func (d Decimal) Float64() (f float64)

Float64 returns the nearest float64 value for d and a bool indicating whether f represents d exactly.

func (*Decimal) FromFloat

func (d *Decimal) FromFloat(v float64)

func (*Decimal) FromInt

func (d *Decimal) FromInt(v int64)

func (*Decimal) FromString

func (d *Decimal) FromString(v string)

func (Decimal) GreaterThan

func (d Decimal) GreaterThan(d2 interface{}) bool

GreaterThan (GT) returns true when d is greater than d2.

func (Decimal) GreaterThanOrEqual

func (d Decimal) GreaterThanOrEqual(d2 interface{}) bool

GreaterThanOrEqual (GTE) returns true when d is greater than or equal to d2.

func (Decimal) IntPart

func (d Decimal) IntPart() int64

IntPart returns the integer component of the decimal.

func (Decimal) IsNegative

func (d Decimal) IsNegative() bool

IsNegative return

true if d < 0
false if d == 0
false if d > 0

func (Decimal) IsPositive

func (d Decimal) IsPositive() bool

IsPositive return

true if d > 0
false if d == 0
false if d < 0

func (Decimal) IsZero

func (d Decimal) IsZero() bool

IsZero return

true if d == 0
false if d > 0
false if d < 0

func (Decimal) LessThan

func (d Decimal) LessThan(d2 interface{}) bool

LessThan (LT) returns true when d is less than d2.

func (Decimal) LessThanOrEqual

func (d Decimal) LessThanOrEqual(d2 interface{}) bool

LessThanOrEqual (LTE) returns true when d is less than or equal to d2.

func (Decimal) MarshalBSON added in v0.1.1

func (d Decimal) MarshalBSON() ([]byte, error)

MarshalBSON implements the bson.Marshaler interface.

func (Decimal) MarshalBSONValue added in v0.1.7

func (d Decimal) MarshalBSONValue() (bsontype.Type, []byte, error)

MarshalBSONValue implements the bson.Marshaler interface.

func (Decimal) MarshalBinary

func (d Decimal) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Decimal) MarshalJSON

func (d Decimal) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Decimal) MarshalText

func (d Decimal) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface for XML serialization.

func (Decimal) Max

func (d Decimal) Max(rest ...Decimal) Decimal

Max returns the largest Decimal that was passed in the arguments. To call this function with an array, you must do: This makes it harder to accidentally call Max with 0 arguments.

func (Decimal) Min

func (d Decimal) Min(rest ...Decimal) Decimal

Min returns the smallest Decimal that was passed in the arguments. To call this function with an array, you must do: This makes it harder to accidentally call Min with 0 arguments.

func (Decimal) Mod

func (d Decimal) Mod(d2 interface{}) Decimal

Mod returns d % d2.

func (Decimal) Mul

func (d Decimal) Mul(d2 interface{}) Decimal

Mul returns d * d2.

func (Decimal) Neg

func (d Decimal) Neg() Decimal

Neg returns -d.

func (Decimal) Pow

func (d Decimal) Pow(d2 interface{}) Decimal

Pow returns d to the power d2

func (Decimal) Round

func (d Decimal) Round(places int32) Decimal

Round rounds the decimal to places decimal places. If places < 0, it will round the integer part to the nearest 10^(-places).

Example:

NewFromFloat(5.45).Round(1).String() // output: "5.5"
NewFromFloat(545).Round(-1).String() // output: "550"

func (*Decimal) Scan

func (d *Decimal) Scan(src interface{}) error

Scan implements the sql.Scanner interface for database deserialization.

func (Decimal) Sign

func (d Decimal) Sign() int

Sign returns:

-1 if d <  0
 0 if d == 0
+1 if d >  0

func (Decimal) Sin

func (d Decimal) Sin() Decimal

Sin returns the sine of the radian argument x.

func (Decimal) String

func (d Decimal) String() string

String returns the string representation of the decimal with the fixed point.

Example:

d := New(-12345, -3)
println(d.String())

Output:

-12.345

func (Decimal) StringFixed

func (d Decimal) StringFixed(places int32) string

StringFixed returns a rounded fixed-point string with places digits after the decimal point.

Example:

NewFromFloat(0).StringFixed(2) // output: "0.00"
NewFromFloat(0).StringFixed(0) // output: "0"
NewFromFloat(5.45).StringFixed(0) // output: "5"
NewFromFloat(5.45).StringFixed(1) // output: "5.5"
NewFromFloat(5.45).StringFixed(2) // output: "5.45"
NewFromFloat(5.45).StringFixed(3) // output: "5.450"
NewFromFloat(545).StringFixed(-1) // output: "550"

func (Decimal) StringScaled

func (d Decimal) StringScaled(exp int32) string

StringScaled first scales the decimal then calls .String() on it. NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.

func (Decimal) Sub

func (d Decimal) Sub(d2 interface{}) Decimal

Sub returns d - d2.

func (Decimal) Sum

func (d Decimal) Sum(rest ...Decimal) Decimal

Sum returns the combined total of the provided first and rest Decimals

func (Decimal) Tan

func (d Decimal) Tan() Decimal

Tan returns the tangent of the radian argument x.

func (Decimal) Truncate

func (d Decimal) Truncate(precision int32) Decimal

Truncate truncates off digits from the number, without rounding.

NOTE: precision is the last digit that will not be truncated (must be >= 0).

Example:

decimal.NewFromString("123.456").Truncate(2).String() // "123.45"

func (*Decimal) UnmarshalBSON added in v0.1.1

func (d *Decimal) UnmarshalBSON(data []byte) error

func (*Decimal) UnmarshalBSONValue added in v0.1.7

func (d *Decimal) UnmarshalBSONValue(bt bsontype.Type, data []byte) error

UnmarshalBSONValue implements the bson.Unmarshaler interface.

func (*Decimal) UnmarshalBinary

func (d *Decimal) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation is already used when encoding to text, this method stores that string as []byte

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Decimal) UnmarshalText

func (d *Decimal) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.

func (Decimal) Value

func (d Decimal) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database serialization.

type Decimal128 added in v0.7.2

type Decimal128 = primitive.Decimal128

func NewDecimal128 added in v0.7.2

func NewDecimal128(high, low uint64) Decimal128

type Engine

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

func NewEngine

func NewEngine(strDSN string, opts ...*Option) (*Engine, error)

func (*Engine) Aggregate added in v0.1.1

func (e *Engine) Aggregate() (err error)

Aggregate execute aggregate pipeline

func (*Engine) And

func (e *Engine) And(strColumn string, value interface{}) *Engine

func (*Engine) Array added in v0.6.0

func (e *Engine) Array(strColumn string, value []interface{}) *Engine

func (*Engine) Asc

func (e *Engine) Asc(strColumns ...string) *Engine

Asc orm select columns for ORDER BY ASC

func (*Engine) Avg added in v0.9.0

func (e *Engine) Avg(strColumn string, values ...interface{}) *Engine

Avg aggregation avg number for $group

func (*Engine) Close added in v0.1.1

func (e *Engine) Close() error

func (*Engine) Collection

func (e *Engine) Collection(strName string, opts ...*options.CollectionOptions) *mongo.Collection

Collection get collection instance specified

func (*Engine) Count

func (e *Engine) Count() (rows int64, err error)

Count orm count documents

func (*Engine) Database

func (e *Engine) Database() *mongo.Database

Database get database instance specified

func (*Engine) Debug

func (e *Engine) Debug(on bool)

func (*Engine) Delete

func (e *Engine) Delete() (rows int64, err error)

Delete delete many records

func (*Engine) Desc

func (e *Engine) Desc(strColumns ...string) *Engine

Desc orm select columns for ORDER BY DESC

func (*Engine) ElemMatch added in v0.6.3

func (e *Engine) ElemMatch(strColumn string, value interface{}) *Engine

func (*Engine) Eq added in v0.6.4

func (e *Engine) Eq(strColumn string, value interface{}) *Engine

func (*Engine) Equal

func (e *Engine) Equal(strColumn string, value interface{}) *Engine

func (*Engine) Except added in v0.1.12

func (e *Engine) Except(strColumns ...string) *Engine

Except insert/update all except columns

func (*Engine) Exists

func (e *Engine) Exists(strColumn string, value bool) *Engine

func (*Engine) Filter

func (e *Engine) Filter(filter bson.M) *Engine

Filter orm condition

func (*Engine) FindOne added in v0.7.1

func (e *Engine) FindOne() (err error)

func (*Engine) FindOneDelete added in v0.6.0

func (e *Engine) FindOneDelete() (res *mongo.SingleResult, err error)

FindOneDelete find single document and delete

func (*Engine) FindOneReplace added in v0.6.0

func (e *Engine) FindOneReplace() (res *mongo.SingleResult, err error)

FindOneReplace find single document and replace

func (*Engine) FindOneUpdate added in v0.6.0

func (e *Engine) FindOneUpdate() (res *mongo.SingleResult, err error)

FindOneUpdate find single document and update

func (*Engine) GeoCenterSphere added in v0.6.0

func (e *Engine) GeoCenterSphere(strColumn string, pos Coordinate, distance int) *Engine

GeoCenterSphere query by coordinate and distance in meters (sphere)

func (*Engine) GeoNearByPoint added in v0.6.1

func (e *Engine) GeoNearByPoint(strColumn string, pos Coordinate, maxDistance int, disFieldName string) *Engine

GeoNearByPoint query and return matched records with max distance in meters (just one index, 2d or 2dshpere) strColumn: the column which include location pos: the position to query maxDistance: the maximum distance nearby pos (meters) includeLocs: the column name which include location disFieldName: distance column name to return

func (*Engine) Geometry added in v0.6.0

func (e *Engine) Geometry(strColumn string, geometry *Geometry) *Engine

Geometry query by geometry

func (*Engine) GroupBy added in v0.9.0

func (e *Engine) GroupBy(exprs ...interface{}) *Engine

GroupBy group by expressions with string, bson.M and bson.D

func (*Engine) Gt added in v0.6.3

func (e *Engine) Gt(strColumn string, value interface{}) *Engine

func (*Engine) GtLt added in v0.6.3

func (e *Engine) GtLt(strColumn string, value1, value2 interface{}) *Engine

func (*Engine) GtLte added in v0.6.3

func (e *Engine) GtLte(strColumn string, value1, value2 interface{}) *Engine

func (*Engine) Gte added in v0.6.3

func (e *Engine) Gte(strColumn string, value interface{}) *Engine

func (*Engine) GteLt added in v0.6.3

func (e *Engine) GteLt(strColumn string, value1, value2 interface{}) *Engine

func (*Engine) GteLte added in v0.6.3

func (e *Engine) GteLte(strColumn string, value1, value2 interface{}) *Engine

func (*Engine) Id added in v0.1.6

func (e *Engine) Id(v interface{}) *Engine

func (*Engine) In

func (e *Engine) In(strColumn string, value interface{}) *Engine

func (*Engine) Insert

func (e *Engine) Insert() ([]interface{}, error)

Insert batch insert and returns id list

func (*Engine) Limit added in v0.1.10

func (e *Engine) Limit(n int) *Engine

func (*Engine) Lt added in v0.6.3

func (e *Engine) Lt(strColumn string, value interface{}) *Engine

func (*Engine) Lte added in v0.6.3

func (e *Engine) Lte(strColumn string, value interface{}) *Engine

func (*Engine) Max added in v0.9.0

func (e *Engine) Max(strColumn string, values ...interface{}) *Engine

Max aggregation max number for $group

func (*Engine) Min added in v0.9.0

func (e *Engine) Min(strColumn string, values ...interface{}) *Engine

Min aggregation min number for $group

func (*Engine) Model

func (e *Engine) Model(args ...interface{}) *Engine

Model orm model use to get result set, support single struct object or slice [pointer type] notice: will clone a new engine object for orm operations(query/update/insert/upsert)

func (*Engine) Ne added in v0.6.3

func (e *Engine) Ne(strColumn string, value interface{}) *Engine

func (*Engine) Options

func (e *Engine) Options(options ...interface{}) *Engine

Options set operation options for find/update/delete/insert...

func (*Engine) Or

func (e *Engine) Or(strColumn string, value interface{}) *Engine

func (*Engine) Page

func (e *Engine) Page(pageNo, pageSize int) *Engine

func (*Engine) Pipeline added in v0.1.1

func (e *Engine) Pipeline(pipelines ...bson.D) *Engine

Pipeline aggregate pipeline

func (*Engine) PrimaryKey added in v0.1.12

func (e *Engine) PrimaryKey() string

func (*Engine) Query

func (e *Engine) Query() (err error)

Query orm query return error if err is not nil must be something wrong NOTE: Model function is must be called before call this function

func (*Engine) QueryEx

func (e *Engine) QueryEx() (total int64, err error)

QueryEx orm query and return total records count return total and error, if err is not nil must be something wrong NOTE: Model function is must be called before call this function, do not call this on aggregate operations

func (*Engine) Regex

func (e *Engine) Regex(strColumn string, value interface{}) *Engine

func (*Engine) Round added in v1.2.0

func (e *Engine) Round(strColumn string, place int, alias ...string) *Engine

Round aggregation round number for $project, place number range -20 ~ 100

func (*Engine) Select

func (e *Engine) Select(strColumns ...string) *Engine

Select orm select columns for projection

func (*Engine) Set

func (e *Engine) Set(strColumn string, value interface{}) *Engine

Set update columns specified

func (*Engine) SetReadTimeout added in v0.9.4

func (e *Engine) SetReadTimeout(timeoutSeconds int)

func (*Engine) SetWriteTimeout added in v0.9.4

func (e *Engine) SetWriteTimeout(timeoutSeconds int)

func (*Engine) Sum added in v0.9.0

func (e *Engine) Sum(strColumn string, values ...interface{}) *Engine

Sum aggregation sum number for $group

func (*Engine) Table

func (e *Engine) Table(strName string) *Engine

Table set orm query table name

func (*Engine) Unwind added in v1.0.1

func (e *Engine) Unwind(obj interface{}) *Engine

Unwind obj param is a string or bson object

func (*Engine) Update

func (e *Engine) Update() (rows int64, err error)

Update update records

func (*Engine) UpdateOne added in v0.6.0

func (e *Engine) UpdateOne() (rows int64, err error)

UpdateOne update one document

func (*Engine) Upsert added in v0.8.0

func (e *Engine) Upsert() (rows int64, err error)

Upsert update or insert

func (*Engine) Use

func (e *Engine) Use(strDatabase string, opts ...*options.DatabaseOptions) *Engine

Use clone another instance and switch to database specified

type FloatArray added in v0.6.0

type FloatArray = []float64

type FloatArray2 added in v0.6.0

type FloatArray2 = []FloatArray

type FloatArray3 added in v0.6.0

type FloatArray3 = []FloatArray2

type FloatArray4 added in v0.6.0

type FloatArray4 = []FloatArray3

type GeoLineString added in v0.6.0

type GeoLineString struct {
	Type        GeoType     `json:"type" bson:"type"`
	Coordinates FloatArray2 `json:"coordinates" bson:"coordinates"`
}

func NewGeoLineString added in v0.6.0

func NewGeoLineString(coords []Coordinate) *GeoLineString

type GeoMultiLineString added in v0.6.0

type GeoMultiLineString struct {
	Type        GeoType     `json:"type" bson:"type"`
	Coordinates FloatArray3 `json:"coordinates" bson:"coordinates"`
}

func NewGeoMultiLineString added in v0.6.0

func NewGeoMultiLineString(coords [][]Coordinate) *GeoMultiLineString

type GeoMultiPoint added in v0.6.0

type GeoMultiPoint struct {
	Type        GeoType     `json:"type" bson:"type"`
	Coordinates FloatArray2 `json:"coordinates" bson:"coordinates"`
}

func NewGeoMultiPoint added in v0.6.0

func NewGeoMultiPoint(coords []Coordinate) *GeoMultiPoint

type GeoMultiPolygon added in v0.6.0

type GeoMultiPolygon struct {
	Type        GeoType     `json:"type" bson:"type"`
	Coordinates FloatArray4 `json:"coordinates" bson:"coordinates"`
}

func NewGeoMultiPolygon added in v0.6.0

func NewGeoMultiPolygon(coords [][][]Coordinate) *GeoMultiPolygon

type GeoPoint added in v0.6.0

type GeoPoint struct {
	Type        GeoType    `json:"type" bson:"type"`
	Coordinates FloatArray `json:"coordinates" bson:"coordinates"`
}

func NewGeoPoint added in v0.6.0

func NewGeoPoint(coord Coordinate) *GeoPoint

type GeoPolygon added in v0.6.0

type GeoPolygon struct {
	Type        GeoType     `json:"type" bson:"type"`
	Coordinates FloatArray3 `json:"coordinates" bson:"coordinates"`
}

func NewGeoPolygon added in v0.6.0

func NewGeoPolygon(coords [][]Coordinate) *GeoPolygon

type GeoType added in v0.6.0

type GeoType string
const (
	GeoTypePoint           GeoType = "Point"
	GeoTypeMultiPoint      GeoType = "MultiPoint"
	GeoTypeLineString      GeoType = "LineString"
	GeoTypeMultiLineString GeoType = "MultiLineString"
	GeoTypePolygon         GeoType = "Polygon"
	GeoTypeMultiPolygon    GeoType = "MultiPolygon"
)

type Geometry added in v0.6.0

type Geometry struct {
	Type        GeoType     `json:"type" bson:"type"`
	Coordinates interface{} `json:"coordinates" bson:"coordinates"`
}

func NewGeoMetry added in v0.6.0

func NewGeoMetry(typ GeoType, coordinates interface{}) *Geometry

type ModelReflector

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

func (*ModelReflector) ToMap

func (s *ModelReflector) ToMap() map[string]interface{}

parse struct tag and value to map

type ModelType

type ModelType int

func (ModelType) GoString

func (m ModelType) GoString() string

func (ModelType) String

func (m ModelType) String() string

type ObjectID added in v0.5.0

type ObjectID = primitive.ObjectID

func NewObjectID added in v0.7.0

func NewObjectID() ObjectID

func NewObjectIDFromString added in v0.7.2

func NewObjectIDFromString(v string) (ObjectID, error)

func NewObjectIDFromTimestamp added in v0.7.2

func NewObjectIDFromTimestamp(t time.Time) ObjectID

type Option added in v0.1.1

type Option struct {
	Debug          bool                     // enable debug mode
	Max            int                      // max active connections
	Idle           int                      // max idle connections
	SSH            *SSH                     // SSH tunnel server config
	ConnectTimeout int                      // connect timeout
	WriteTimeout   int                      // write timeout seconds
	ReadTimeout    int                      // read timeout seconds
	DatabaseOpt    *options.DatabaseOptions // database options
}

type SSH

type SSH struct {
	User       string //SSH tunnel server login account
	Password   string //SSH tunnel server login password
	PrivateKey string //SSH tunnel server private key, eg. "/home/test/.ssh/private-key.pem"
	Host       string //SSH tunnel server host [ip or domain], default port 22 if not specified
	// contains filtered or unexported fields
}

func (*SSH) GoString

func (s *SSH) GoString() string

func (*SSH) String

func (s *SSH) String() string

type UrlInfo

type UrlInfo struct {
	Scheme     string
	Host       string // host name and port like '127.0.0.1:3306'
	User       string
	Password   string
	Path       string
	Fragment   string
	Opaque     string
	ForceQuery bool
	Queries    map[string]string
	Database   string
}

func ParseUrl

func ParseUrl(strUrl string) (ui *UrlInfo)

URL have some special characters in password(支持URL中密码包含特殊字符)

Jump to

Keyboard shortcuts

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