pie

package module
v0.1.14 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

README

Alt

pie

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

1.0 目标 todo list

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

安装

go get github.com/5xxxx/pie

连接到数据库

package main

import (
    "github.com/5xxxx/pie"
    "go.mongodb.org/mongo-driver/mongo/options"
)


client, err := pie.NewClient("baz", options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
or

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

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

fmt.Println(user)

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

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


base := 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")
SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = Connect(context.Background()); err != nil {
    panic(err)
}

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

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

InsertMany

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

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

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

FindOne

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

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

or
driver, err := pie.NewDriver("demo")
SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = 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 = FilterBy(user).FindOne(context.Background(), &user)
if err != nil {
    panic(err)
}

FindAll

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

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

or

driver, err := pie.NewDriver("demo")
SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = 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 = FilterBy(user).FindAll(context.Background(), &users)
if err != nil {
    panic(err)
}
fmt.Println(users)

UpdateOne

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

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

DeleteOne

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

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

DeleteMany

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

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

Aggregate

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

var user []User

err = 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")
SetURI("mongodb://127.0.0.1:27017")
if err != nil {
    panic(err)
}
if err = Connect(context.Background()); err != nil {
    panic(err)
}

indexes, err := 
    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

View Source
var (
	ErrUnsupportedType = errors.New("Unsupported type")
)

Functions

This section is empty.

Types

type Aggregate added in v0.1.14

type Aggregate interface {
	One(result interface{}, ctx ...context.Context) error
	All(result interface{}, ctx ...context.Context) error
	// SetAllowDiskUse sets the value for the AllowDiskUse field.
	SetAllowDiskUse(b bool) Aggregate

	// SetBatchSize sets the value for the BatchSize field.
	SetBatchSize(i int32) Aggregate

	// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
	SetBypassDocumentValidation(b bool) Aggregate

	// SetCollation sets the value for the Collation field.
	SetCollation(c *options.Collation) Aggregate

	// SetMaxTime sets the value for the MaxTime field.
	SetMaxTime(d time.Duration) Aggregate

	// SetMaxAwaitTime sets the value for the MaxAwaitTime field.
	SetMaxAwaitTime(d time.Duration) Aggregate

	// SetComment sets the value for the Comment field.
	SetComment(s string) Aggregate

	// SetHint sets the value for the Hint field.
	SetHint(h interface{}) Aggregate

	Pipeline(pipeline bson.A) Aggregate

	Match(c Condition) Aggregate

	SetDatabase(db string) Aggregate

	Collection(doc interface{}) Aggregate

	SetCollReadPreference(rp *readpref.ReadPref) Aggregate

	SetCollRegistry(r *bsoncodec.Registry) Aggregate

	SetCollWriteConcern(wc *writeconcern.WriteConcern) Aggregate

	SetReadConcern(rc *readconcern.ReadConcern) Aggregate
}

func NewAggregate added in v0.1.14

func NewAggregate(engine Client) Aggregate

NewAggregate creates a new instance of the Aggregate struct with the provided client as the engine.

type Client added in v0.1.14

type Client interface {
	FindPagination(needCount bool, doc interface{}, ctx ...context.Context) (int64, error)
	FindOneAndReplace(doc interface{}, ctx ...context.Context) error
	FindOneAndUpdate(doc interface{}, ctx ...context.Context) (*mongo.SingleResult, error)
	FindAndDelete(doc interface{}, ctx ...context.Context) error
	FindOne(doc interface{}, ctx ...context.Context) error
	FindAll(docs interface{}, ctx ...context.Context) error
	RegexFilter(key, pattern string) Session
	Distinct(doc interface{}, columns string, ctx ...context.Context) ([]interface{}, error)
	FindOneAndUpdateBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.SingleResult, error)

	InsertOne(v interface{}, ctx ...context.Context) (primitive.ObjectID, error)
	InsertMany(v interface{}, ctx ...context.Context) (*mongo.InsertManyResult, error)
	BulkWrite(docs interface{}, ctx ...context.Context) (*mongo.BulkWriteResult, error)
	ReplaceOne(doc interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	Update(bean interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	UpdateMany(bean interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	UpdateOneBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	UpdateManyBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	SoftDeleteOne(filter interface{}, ctx ...context.Context) error
	SoftDeleteMany(filter interface{}, ctx ...context.Context) error
	DeleteOne(filter interface{}, ctx ...context.Context) (*mongo.DeleteResult, error)
	DeleteMany(filter interface{}, ctx ...context.Context) (*mongo.DeleteResult, error)

	DataBase() *mongo.Database
	// Collection(name string, db ...string) *mongo.Collection
	Collection(name string, collOpts []*options.CollectionOptions, db ...string) *mongo.Collection
	Ping() error
	Connect(ctx ...context.Context) (err error)
	Disconnect(ctx ...context.Context) error

	// Soft filter
	Soft(s bool) Session
	FilterBy(object interface{}) Session
	Filter(key string, value interface{}) Session
	Asc(colNames ...string) Session
	Eq(key string, value interface{}) Session
	Ne(key string, ne interface{}) Session
	Nin(key string, nin interface{}) Session
	Nor(c Condition) Session
	Exists(key string, exists bool, filter ...Condition) Session
	Type(key string, t interface{}) Session
	Expr(filter Condition) Session
	Regex(key string, value string) Session
	ID(id interface{}) Session
	Gt(key string, value interface{}) Session
	Gte(key string, value interface{}) Session
	Lt(key string, value interface{}) Session
	Lte(key string, value interface{}) Session
	In(key string, value interface{}) Session
	And(filter Condition) Session
	Not(key string, value interface{}) Session
	Or(filter Condition) Session
	Limit(limit int64) Session
	Skip(skip int64) Session
	Count(i interface{}, ctx ...context.Context) (int64, error)
	Desc(s1 ...string) Session
	FilterBson(d bson.D) Session

	NewIndexes() Indexes
	DropAll(doc interface{}, ctx ...context.Context) error
	DropOne(doc interface{}, name string, ctx ...context.Context) error
	AddIndex(keys interface{}, opt ...*options.IndexOptions) Indexes

	NewSession() Session
	Aggregate() Aggregate

	CollectionNameForStruct(doc interface{}) (*schemas.Collection, error)
	CollectionNameForSlice(doc interface{}) (*schemas.Collection, error)
	Transaction(ctx context.Context, f schemas.TransFunc) error
	TransactionWithOptions(ctx context.Context, f schemas.TransFunc, opt ...*options.SessionOptions) error
}

Client is an interface that provides various methods for interacting with a MongoDB database.

FindPagination retrieves paginated documents from the specified collection based on the given page and count. FindOneAndReplace replaces a single document that matches the filter with the provided document. FindOneAndUpdate updates a single document that matches the filter with the provided update document. FindAndDelete deletes a single document that matches the filter. FindOne retrieves a single document that matches the filter. FindAll retrieves all documents that match the filter. RegexFilter applies a regular expression filter to the session. Distinct returns an array of distinct values for a specified field across a collection. FindOneAndUpdateBson updates a single document that matches the BSON filter with the provided update BSON document. InsertOne inserts a single document into the collection. InsertMany inserts multiple documents into the collection. BulkWrite performs multiple write operations in bulk on the collection. ReplaceOne replaces a single document that matches the filter with the provided replacement document. Update updates a single document that matches the filter with the provided update document. UpdateMany updates multiple documents that match the filter with the provided update document. UpdateOneBson updates a single document that matches the BSON filter with the provided update BSON document. UpdateManyBson updates multiple documents that match the BSON filter with the provided update BSON document. SoftDeleteOne performs a soft delete on a single document that matches the filter. SoftDeleteMany performs a soft delete on multiple documents that match the filter. DeleteOne deletes a single document that matches the filter. DeleteMany deletes multiple documents that match the filter. DataBase returns the underlying mongo.Database associated with the client. Collection returns the mongo.Collection with the specified name and options. Ping checks if the client is connected to the database and returns an error if not. Connect establishes a connection to the database. Disconnect closes the connection to the database. Soft sets the soft filter state of the session. FilterBy applies the specified object as a filter to the session. Filter adds a key-value filter to the session. Asc adds the specified column names as sort order in ascending order to the session. Eq adds an equal filter to the session. Ne adds a not equal filter to the session. Nin adds a not in filter to the session. Nor adds a nor condition to the session. Exists adds an exists condition to the session. Type adds a type condition to the session. Expr adds an expression filter to the session. Regex adds a regex filter to the session. ID adds an _id filter to the session. Gt adds a greater than filter to the session. Gte adds a greater than or equal to filter to the session. Lt adds a less than filter to the session. Lte adds a less than or equal to filter to the session. In adds an in filter to the session. And adds an and condition to the session. Not adds a not condition to the session. Or adds an or condition to the session. Limit sets the maximum number of documents the session should return. Skip sets the number of documents the session should skip. Count returns the number of documents that match the filter. Desc adds the specified column names as sort order in descending order to the session. FilterBson adds a BSON filter to the session. NewIndexes returns a new Indexes instance for managing collection indexes. DropAll drops all indexes from the specified document's collection. DropOne drops the specified index from the specified document's collection. AddIndex adds an index to the specified document's collection. NewSession returns a new session for performing multiple operations. Aggregate returns an aggregate operation for the specified document's collection. CollectionNameForStruct returns the collection name for the specified document struct. CollectionNameForSlice returns the collection name for the specified document slice. Transaction starts a transaction and executes the provided function within the transaction context. TransactionWithOptions starts a transaction with the provided options and executes the provided function within the transaction context.

func NewClient

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

NewClient creates a new client with the specified database name and options. It returns a Client interface and an error.

type ClientOptions added in v0.1.14

type ClientOptions interface {
	// SetArrayFilters sets the value for the ArrayFilters field.
	SetArrayFilters(filters options.ArrayFilters) Session
	// SetOrdered sets the value for the Ordered field.
	SetOrdered(ordered bool) Session
	// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
	SetBypassDocumentValidation(b bool) Session
	// SetReturnDocument sets the value for the ReturnDocument field.
	SetReturnDocument(rd options.ReturnDocument) Session

	// SetUpsert sets the value for the Upsert field.
	SetUpsert(b bool) Session

	// SetCollation sets the value for the Collation field.
	SetCollation(collation *options.Collation) Session

	// SetMaxTime sets the value for the MaxTime field.
	SetMaxTime(d time.Duration) Session
	// SetProjection sets the value for the Projection field.
	SetProjection(projection interface{}) Session

	// SetSort sets the value for the Sort field.
	SetSort(sort interface{}) Session

	// SetHint sets the value for the Hint field.
	SetHint(hint interface{}) Session
}

ClientOptions represents the options for configuring a client session.

type Condition

type Condition interface {
	RegexFilter(key, pattern string) Condition
	ID(id interface{}) Condition
	// 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{}) Condition

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

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

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

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

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

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

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

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

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

	// 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) Condition
	// Or { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] }
	Or(filter Condition) Condition

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

	// 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{}) Condition

	// 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) Condition

	// Regex todo 简单实现,后续增加支持
	Regex(key string, value string) Condition

	Filters() (bson.D, error)
	A() bson.A
	Err() error
	FilterBson(d interface{}) Condition
	FilterBy(object interface{}) Condition

	Clone() Condition
}

func DefaultCondition

func DefaultCondition() Condition

DefaultCondition returns a default condition initialized with an empty bson.D slice. This condition can be used to chain query filter methods and construct complex filter expressions

func NewCondition

func NewCondition() Condition

type Indexes added in v0.1.14

type Indexes interface {
	CreateIndexes(doc interface{}, ctx ...context.Context) ([]string, error)
	DropAll(doc interface{}, ctx ...context.Context) error
	DropOne(doc interface{}, name string, ctx ...context.Context) error
	AddIndex(keys interface{}, opt ...*options.IndexOptions) Indexes
	SetMaxTime(d time.Duration) Indexes
	SetCommitQuorumInt(quorum int32) Indexes
	SetCommitQuorumString(quorum string) Indexes
	SetCommitQuorumMajority() Indexes
	SetCommitQuorumVotingMembers() Indexes
	SetDatabase(db string) Indexes
	Collection(doc interface{}) Indexes
}

Indexes represents the interface for managing indexes in a database.

func NewIndexes added in v0.1.14

func NewIndexes(driver Client) Indexes

type Options added in v0.1.14

type Options struct {
	UpdateEmpty bool
}

func (*Options) SetUpdateEmpty added in v0.1.14

func (o *Options) SetUpdateEmpty(e bool)

SetUpdateEmpty sets the value for the UpdateEmpty field.

type Parser added in v0.1.14

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

func NewParser added in v0.1.14

func NewParser(collectionMapper, columnMapper names.Mapper) *Parser

func (*Parser) Parse added in v0.1.14

func (parser *Parser) Parse(v reflect.Value) (*schemas.Collection, error)

type Session added in v0.1.14

type Session interface {
	BulkWrite(docs interface{}, ctx ...context.Context) (*mongo.BulkWriteResult, error)

	FilterBy(object interface{}) Session

	Distinct(doc interface{}, columns string, ctx ...context.Context) ([]interface{}, error)

	ReplaceOne(doc interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	FindOneAndReplace(doc interface{}, ctx ...context.Context) error

	FindOneAndUpdate(doc interface{}, ctx ...context.Context) (*mongo.SingleResult, error)

	FindOneAndUpdateBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.SingleResult, error)

	FindPagination(needCount bool, rowsSlicePtr interface{}, ctx ...context.Context) (int64, error)

	FindAndDelete(doc interface{}, ctx ...context.Context) error

	// FindOne executes a find command and returns a SingleResult for one document in the collectionByName.
	FindOne(doc interface{}, ctx ...context.Context) error

	// FindAll Find executes a find command and returns a Cursor over the matching documents in the collectionByName.
	FindAll(rowsSlicePtr interface{}, ctx ...context.Context) error

	// InsertOne executes an insert command to insert a single document into the collectionByName.
	InsertOne(doc interface{}, ctx ...context.Context) (primitive.ObjectID, error)

	// InsertMany executes an insert command to insert multiple documents into the collectionByName.
	InsertMany(docs interface{}, ctx ...context.Context) (*mongo.InsertManyResult, error)

	// DeleteOne executes a delete command to delete at most one document from the collectionByName.
	DeleteOne(doc interface{}, ctx ...context.Context) (*mongo.DeleteResult, error)
	SoftDeleteOne(doc interface{}, ctx ...context.Context) error

	// DeleteMany executes a delete command to delete documents from the collectionByName.
	DeleteMany(doc interface{}, ctx ...context.Context) (*mongo.DeleteResult, error)

	SoftDeleteMany(doc interface{}, ctx ...context.Context) error

	Clone() Session
	Limit(i int64) Session

	Skip(i int64) Session

	Count(i interface{}, ctx ...context.Context) (int64, error)

	UpdateOne(bean interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	UpdateOneBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	UpdateManyBson(coll interface{}, bson interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	UpdateMany(bean interface{}, ctx ...context.Context) (*mongo.UpdateResult, error)

	RegexFilter(key, pattern string) Session

	ID(id interface{}) Session

	Asc(colNames ...string) Session

	Desc(colNames ...string) Session

	Sort(colNames ...string) Session
	Soft(f bool) Session
	Filter(key string, value interface{}) Session
	FilterBson(d bson.D) Session
	// 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{}) Session

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

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

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

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

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

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

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

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

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

	// Nor { $nor: [ { price: 1.99 }, { price: { $exists: false } },
	// { sale: true }, { sale: { $exists: false } } ] }
	// price != 1.99 || sale != true || sale exists || sale exists
	Nor(c Condition) Session

	// Or { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] }
	Or(c Condition) Session

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

	// SetArrayFilters sets the value for the ArrayFilters field.
	SetArrayFilters(filters options.ArrayFilters) Session

	// SetOrdered sets the value for the Ordered field.
	SetOrdered(ordered bool) Session

	// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
	SetBypassDocumentValidation(b bool) Session

	// SetReturnDocument sets the value for the ReturnDocument field.
	SetReturnDocument(rd options.ReturnDocument) Session

	// SetUpsert sets the value for the Upsert field.
	SetUpsert(b bool) Session

	// SetCollation sets the value for the Collation field.
	SetCollation(collation *options.Collation) Session

	// SetMaxTime sets the value for the MaxTime field.
	SetMaxTime(d time.Duration) Session

	// SetProjection sets the value for the Projection field.
	SetProjection(projection interface{}) Session

	// SetSort sets the value for the Sort field.
	SetSort(sort interface{}) Session

	// SetHint sets the value for the Hint field.
	SetHint(hint interface{}) Session

	// 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{}) Session

	// 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(c Condition) Session

	// Regex todo 简单实现,后续增加支持
	Regex(key string, value string) Session

	SetDatabase(db string) Session

	SetCollRegistry(r *bsoncodec.Registry) Session

	SetCollReadPreference(rp *readpref.ReadPref) Session

	SetCollWriteConcern(wc *writeconcern.WriteConcern) Session

	SetReadConcern(rc *readconcern.ReadConcern) Session
}

func NewSession added in v0.1.14

func NewSession(engine Client) Session

NewSession creates a new session with the specified engine and default condition filter. It returns a Session interface which can be used to interact with the engine.

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