pie

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2021 License: Apache-2.0 Imports: 11 Imported by: 0

README

pie

pie 是基于官方mongo-go-driver 封装,所有操作都是通过链式调用,可以方便的对MongoDB进行操作

1.0 目标 todo list

  • Aggregate封装
  • CRUD全功能 e.g FindOneAndDelete
  • 测试
  • 文档

安装

go get github.com/5xxxx/pie

连接到数据库

driver := pie.NewDriver("demo",options.Client().ApplyURI("mongodb://127.0.0.1:27017"))

or

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

var user User
err = driver.Filter("nickName", "淳朴的润土").FindOne(&user)
if err != nil {
    panic(err)
}

fmt.Println(user)

pie还处于开发阶段,如果有不能满足需求的功能可以调用DataBase()方法获取*mongo.Database进行操作

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}


base := driver.DataBase()
matchStage := bson.D{{"$match", bson.D{{"operationType", "insert"}}}}
opts := options.ChangeStream().SetMaxAwaitTime(2 * time.Second)

changeStream, err := base.Watch(context.TODO(), mongo.Pipeline{matchStage}, opts)
if err != nil {
    panic(err)
}
for changeStream.Next(context.Background()) {
    fmt.Println(changeStream.Current)
}

数据定义

type User struct {
	ID             string              `bson:"_id" filter:"_id"`
	Username       string              `bson:"user_name" filter:"user_name"`
	MobileNumber   string              `bson:"mobile_number" filter:"mobile_number"`
}

InsertOne

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

var user User
user.Username = "小明"
user.MobileNumber = "138888888"

err := driver.Insert(&user)
if err != nil {
    fmt.Println(err)
}

InsertMany

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

var users = []User{
    {NickName: "aab"},
    {NickName: "bbb"},
    {NickName: "ccc"},
    {NickName: "dd"},
    {NickName: "eee"},
}

_, err = driver.InsertMany(context.Background(), users)
if err != nil {
    panic(err)
}

FindOne

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

var u User
_, err := driver.Filter("username", "小明").Get(&u)
if err != nil {
    panic(err)
}

or
driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

type User struct {
	ID             string              `bson:"_id" filter:"_id"`
	Username       string              `bson:"user_name" filter:"user_name"`
	MobileNumber   string              `bson:"mobile_number" filter:"-"` //ignore filter
}

var user User
user.Id, _ = primitive.ObjectIDFromHex("5f0ace734e2d4100013d8797")
user.Username = "Jack"
user.MobileNumber = "+86 10086"
err = driver.FilterBy(user).FindOne(context.Background(), &user)
if err != nil {
    panic(err)
}

FindAll

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

var user []User
driver.Gt("age",10).Skip(10).Limit(100).FindAll(&user)
if err != nil {
    panic(err)
}

or

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

type User struct {
	ID             string              `bson:"_id" filter:"_id"`
	Username       string              `bson:"user_name" filter:"user_name"`
	MobileNumber   string              `bson:"mobile_number" filter:"-"` //ignore filter
}

var users []User
var user User
user.Age = 22
err = driver.FilterBy(user).FindAll(context.Background(), &users)
if err != nil {
    panic(err)
}
fmt.Println(users)

UpdateOne

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

u := new(User)
u.Username = "xiao_ming"
err := driver.Filter("mobileNumber", "138888888").Id(u.Id).Update(u)
if err != nil {
    fmt.Println(err)
}

DeleteOne

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

u := new(User)
u.MobileNumber = "138888888"
err := driver.Id(u.Id).Delete(u)
if err != nil {
    fmt.Println(err)
}

DeleteMany

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

u := new(User)
u.MobileNumber = "138888888"
err := driver.DeleteMany(u)
if err != nil {
    fmt.Println(err)
}

Aggregate

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

var user []User

err = driver.Aggregate().
Match(pie.DefaultCondition().
Eq("nick_name", "黄晶晶").
Eq("mobile_number", "c5b013cb2e102e0e743f117220b2acd1")).All(&user)
if err != nil {
    panic(err)
}
fmt.Println(user)

CreateIndexes

driver, err := pie.NewDriver("demo")
driver.SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = driver.Connect(context.Background()); err != nil {
    panic(err)
}

indexes, err := driver.
    AddIndex(bson.M{"nickName": 1}, options.Index().SetBackground(true)).
    AddIndex(bson.M{"birthday": 1}).
    AddIndex(bson.M{"createdAt": 1, "mobileNumber": 1},
    options.Index().SetBackground(true).SetName("create_mobil_index")).
    CreateIndexes(context.Background(), &User{})

if err != nil {
    panic(err)
}
fmt.Println(indexes)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewClient

func NewClient(db string, options ...*options.ClientOptions) (driver.Client, error)

func NewCondition

func NewCondition() driver.Condition

Types

type Condition

type Condition interface {
	RegexFilter(key, pattern string) *filter
	ID(id interface{}) *filter
	// Eq Equals a Specified Value
	//{ qty: 20 }
	//Field in Embedded Document Equals a Value
	//{"item.name": "ab" }
	// Equals an Array Value
	//{ tags: [ "A", "B" ] }
	Eq(key string, value interface{}) *filter

	// Gt {field: {$gt: value} } >
	Gt(key string, gt interface{}) *filter

	// Gte { qty: { $gte: 20 } } >=
	Gte(key string, gte interface{}) *filter

	// In { field: { $in: [<value1>, <value2>, ... <valueN> ] } }
	// tags: { $in: [ /^be/, /^st/ ] } }
	// in []string []int ...
	In(key string, in interface{}) *filter

	// Lt {field: {$lt: value} } <
	Lt(key string, lt interface{}) *filter

	// Lte { field: { $lte: value} } <=
	Lte(key string, lte interface{}) *filter

	// Ne {field: {$ne: value} } !=
	Ne(key string, ne interface{}) *filter

	// Nin { field: { $nin: [ <value1>, <value2> ... <valueN> ]} } the field does not exist.
	Nin(key string, nin interface{}) *filter

	// And { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
	//$and: [
	//        { $or: [ { qty: { $lt : 10 } }, { qty : { $gt: 50 } } ] },
	//        { $or: [ { sale: true }, { price : { $lt : 5 } } ] }
	// ]
	And(filter Condition) *filter

	// Not { field: { $not: { <operator-expression> } } }
	//not and Regular Expressions
	//{ item: { $not: /^p.*/ } }
	Not(key string, not interface{}) *filter

	// Nor { $nor: [ { price: 1.99 }, { price: { $exists: false } },
	// { sale: true }, { sale: { $exists: false } } ] }
	// price != 1.99 || sale != true || sale exists || sale exists
	Nor(filter Condition) *filter
	// Or { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] }
	Or(filter Condition) *filter

	Exists(key string, exists bool, filter ...Condition) *filter

	// Type { field: { $type: <BSON type> } }
	// { "_id" : 1, address : "2030 Martian Way", zipCode : "90698345" },
	// { "_id" : 2, address: "156 Lunar Place", zipCode : 43339374 },
	// db.find( { "zipCode" : { $type : 2 } } ); or db.find( { "zipCode" : { $type : "string" } }
	// return { "_id" : 1, address : "2030 Martian Way", zipCode : "90698345" }
	Type(key string, t interface{}) *filter

	// Expr Allows the use of aggregation expressions within the query language.
	//{ $expr: { <expression> } }
	//$expr can build query expressions that compare fields from the same document in a $match stage
	//todo 没用过,不知道行不行。。https://docs.mongodb.com/manual/reference/operator/query/expr/#op._S_expr
	Expr(filter Condition) *filter

	// Regex todo 简单实现,后续增加支持
	Regex(key string, value interface{}) *filter

	Filters() bson.D
	A() bson.A
}

func DefaultCondition

func DefaultCondition() Condition

type TagMaker

type TagMaker interface {
	// MakeTag makes tag for the field the fieldIndex in the structureType.
	// Result should depends on constant parameters of creation of the TagMaker and parameters
	// passed to the MakeTag. The MakeTag should not produce side effects (like a pure function).
	MakeTag(structureType reflect.Type, fieldIndex int) reflect.StructTag
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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