mongoutils

package module
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2023 License: MIT Imports: 13 Imported by: 0

README

MongoUtils

Mongodb helper functions, document and pipeline builder.

Helpers

MongoOperationCtx

Create context for mongo db operations for 10 sec.

MongoOperationCtx() (context.Context, context.CancelFunc)
ParseObjectID

Parse object id from string.

ParseObjectID(id string) *primitive.ObjectID
IsValidObjectId

Check if object id is valid and not zero.

IsValidObjectId(id *primitive.ObjectID) bool
FindOption

Generate find option with sorts params.

FindOption(sort any, skip int64, limit int64) *options.FindOptions
AggregateOption

Generate aggregation options.

AggregateOption() *options.AggregateOptions
TxOption

Generate transaction option with majority write and snapshot read.

AggregateOption() *options.AggregateOptions
Array

Generate primitive.A from parameters.

Array(args ...any) primitive.A
Map

Generate primitive.M from parameters. Parameters count must be even.

// Signature:
Map(args ...any) primitive.M

// Example:
mongoutils.Map("name", "John", "age", 23) // { "name": "John", "age": 23 }
Maps

Generate []primitive.M from parameters. Parameters count must be even.

// Signature:
Maps(args ...any) []primitive.M

// Example:
mongoutils.Maps("name", "John", "age", 23) // [{ "name": "John" }, { "age": 23 }]
Doc

Generate primitive.D from parameters. Parameters count must be even.

// Signature:
Doc(args ...any) primitive.D

// Example:
mongoutils.Doc("name", "John", "age", 23) // { "name": "John", "age": 23 }
Regex

Generate mongo Regex doc.

// Signature:
Regex(pattern string, opt string) primitive.Regex

// Example:
mongoutils.Regex("John.*", "i") // { pattern: "John.*", options: "i" }
RegexFor

Generate map with regex parameter.

// Signature
RegexFor(k string, pattern string, opt string) primitive.M

// Example:
mongoutils.RegexFor("name", "John.*", "i") // { "name": { pattern: "John.*", options: "i" } }
In

Generate $in map {k: {$in: v}}.

In(k string, v ...any) primitive.M
Set

Generate simple set map {$set: v}.

Set(v any) primitive.M
SetNested

Generate nested set map {$set: {k: v}}.

SetNested(k string, v any) primitive.M
Match

Generate nested set map {$match: v}.

Match(v any) primitive.M

Model Interface

Base interface for mongodb model.

Note: You can inherit EmptyModel in your struct. EmptyModel implements all model methods.

Note: You can inherit BaseModel in your struct. BaseModel contains _id, created_at, updated_at fields and SetID, NewId, PrepareInsert and PrepareUpdate. you can override or implement other model method.

Note: Set BaseModel bson tag to inline for insert timestamps in document root.

// Usage:
import "github.com/bopher/mongoutils"
type Person struct{
 mongoutils.BaseModel  `bson:",inline"`
}

// override methods
func (me Person) IsDeletable() bool{
    return true
}
Available methods

Note: All method must implement with pointer receiver!

Note: Context can passed to model method on call for mongodb transaction mode!

// TypeName get type string
TypeName() string
// Collection get model collection
Collection(db *mongo.Database) *mongo.Collection
// Indexes create model indexes
Index(db *mongo.Database) error
// Seed run model seed
Seed(db *mongo.Database) error
// Pipeline get model pipeline
Pipeline() MongoPipeline
// NewId generate new id for model (Pointer)
NewId()
// SetID set model id (Pointer)
SetID(id primitive.ObjectID)
// GetID get model id
GetID() primitive.ObjectID
// IsEditable check if document is editable
// by default returns true on BaseModel
IsEditable() bool
// IsDeletable check if document is deletable
// by default returns false on BaseModel
IsDeletable() bool
// Cleanup document before save
// e.g set document field nil for ignore saving
Cleanup()
// PrepareInsert fill created_at before save (Pointer)
PrepareInsert()
// PrepareUpdate fill updated_at before save (Pointer)
// in ghost mode updated_at field not changed
PrepareUpdate(ghost bool)
// OnInsert function to call before insert (Pointer)
OnInsert(ctx context.Context, opt ...MongoOption)
// OnUpdate function to call before update (Pointer)
OnUpdate(ctx context.Context, opt ...MongoOption)
// OnDelete function to call before delete (Pointer)
OnDelete(ctx context.Context, opt ...MongoOption)
// OnInserted function to call after insert
OnInserted(ctx context.Context, opt ...MongoOption)
// OnUpdated function to call after update
OnUpdated(old any, ctx context.Context, opt ...MongoOption)
// OnDeleted function to call after delete
OnDeleted(ctx context.Context, opt ...MongoOption)
Required Methods

Two PrepareInsert and PrepareUpdate must called before save model to database.

Note: if true passed to PrepareUpdate method, updated_at method not updated.

Doc Builder

Document builder is a helper type for creating mongo document (primitive.D) with chained methods.

import "github.com/bopher/mongoutils"
doc := mongoutils.NewDoc()
doc.
    Add("name", "John").
    Add("nick", "John2").
    Array("skills", "javascript", "go", "rust", "mongo")
fmt.Println(doc.Build())
// -> {
//   "name": "John",
//   "nick": "John2",
//   "skills": ["javascript","go","rust","mongo"]
// }
Doc Methods
Add

Add new element.

// Signature:
Add(k string, v any) MongoDoc

// Example:
doc.Add("name", "Kim")
Doc

Add new element with nested doc value.

// Signature:
Doc(k string, cb func(d MongoDoc) MongoDoc) MongoDoc

// Example:
doc.Doc("age", func(d mongoutils.MongoDoc) mongoutils.MongoDoc {
    d.Add("$gt", 20)
    d.Add("$lte", 30)
    return d
}) // -> { "age": { "$gt": 20, "$lte": 30 } }
Array

Add new element with array value.

// Signature:
Array(k string, v ...any) MongoDoc

// Example:
doc.Array("skills", "javascript", "golang") // -> { "skills": ["javascript", "golang"] }
DocArray

Add new array element with doc child.

// Signature:
DocArray(k string, cb func(d MongoDoc) MongoDoc) MongoDoc

// Example:
doc.DocArray("$match", func(d mongoutils.MongoDoc) mongoutils.MongoDoc {
    return d.Add("name", "John")
            Add("Family", "Doe")
}) // -> { "$match": [{"name": "John"}, {"Family": "Doe"}] }
Nested

Add new nested element.

// Signature:
Nested(root string, k string, v any) MongoDoc

// Example:
doc.Nested("$set", "name", "Jack") // { "$set": { "name": "Jack" } }
NestedDoc

Add new nested element with doc value.

// Signature:
NestedDoc(root string, k string, cb func(d MongoDoc) MongoDoc) MongoDoc

// Example:
doc.NestedDoc("$set", "address", func(d mongoutils.MongoDoc) mongoutils.MongoDoc {
    d.
        Add("city", "London").
        Add("street", "12th")
    return d
}) // -> { "$set": { "address": { "city": "London", "street": "12th" } } }
NestedArray

Add new nested element with array value.

// Signature:
NestedArray(root string, k string, v ...any) MongoDoc

// Example:
doc.NestedArray("skill", "$in", "mongo", "golang") // -> { "skill": { "$in": ["mongo", "golang"] } }
NestedDocArray

Add new nested array element with doc

// Signature:
NestedDocArray(root string, k string, cb func(d MongoDoc) MongoDoc) MongoDoc

// Example:
doc.NestedDocArray("name", "$match", func(d mongoutils.MongoDoc) mongoutils.MongoDoc {
    return d.Add("first", "John")
            Add("last", "Doe")
}) // -> { "name" : {"$match": [{"name": "John"}, {"last": "Doe"}] } }
Regex

Add new element with regex value.

// Signature:
Regex(k string, pattern string, opt string) MongoDoc

// Example:
doc.Regex("full_name", "John.*", "i") // -> { "full_name": { pattern: "John.*", options: "i" } }
Map

Creates a map from the elements of the Doc.

Map() primitive.M
Build

Generate mongo doc.

Build() primitive.D

Pipeline Builder

Pipeline builder is a helper type for creating mongo pipeline ([]primitive.D) with chained methods.

import "github.com/bopher/mongoutils"
pipe := mongoutils.NewPipe()
pipe.
    Add(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
        d.Nested("$match", "name", "John")
        return d
    }).
    Group(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
        d.
            Add("_id", "$_id").
            Nested("name", "$first", "$name")
            Nested("total", "$sum", "$invoice")
        return d
    })
fmt.Println(pipe.Build())
// -> [
//   { "$match": { "name": "John"} },
//   { "$group": {
//       "_id": "$_id"
//       "name": { "$first": "$name" },
//       "total": { "$sum": "$invoice" }
//   }}
// ]
Pipeline Methods
Add

Add new Doc.

// Signature:
Add(cb func(d MongoDoc) MongoDoc) MongoPipeline

// Example:
pipe.Add(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
    d.Nested("$match", "name", "John")
    return d
}) // -> [ {"$match": { "name": "John"}} ]
Match

Add $match stage. skip nil input

// Signature:
Match(filters any) MongoPipeline

// Example:
pipe.Match(v)
In

Add $in stage.

// Signature:
In(key string, v any) MongoPipeline

// Example:
pipe.In("status", statuses)
Limit

Add $limit stage (ignore negative and zero value).

// Signature:
Limit(limit int64) MongoPipeline

// Example:
pipe.Limit(100)
Skip

Add $skip stage (ignore negative and zero value).

// Signature:
Skip(skip int64) MongoPipeline

// Example:
pipe.Skip(25)
Sort

Add $sort stage (ignore nil value).

// Signature:
Sort(sorts any) MongoPipeline

// Example:
pipe.Sort(primitive.M{"username": 1})
Unwind

Add $unwind stage.

// Signature:
Unwind(path string, prevNullAndEmpty bool) MongoPipeline

// Example:
pipe.Unwind("services", true)
// -> [
//     {"$unwind": {
//         "path": "services",
//         "preserveNullAndEmptyArrays": true,
//     }}
// ]
Lookup

Add $lookup stage.

// Signature:
Lookup(from string, local string, foreign string, as string) MongoPipeline

// Example:
pipe.Lookup("users", "user_id", "_id", "user")
// -> [
//     {"$lookup": {
//         "from": "users",
//         "localField": "user_id",
//         "foreignField": "_id",
//         "as": "user"
//     }}
// ]
Unwrap

Get first item of array and insert to doc using $addFields stage. When using lookup result returns as array, use me helper to unwrap lookup result as field.

// Signature:
Unwrap(field string, as string) MongoPipeline

// Example:
pipe.
    Lookup("users", "user_id", "_id", "__user").
    Unwrap("$__user", "user")
// -> [
//     { "$lookup": {
//         "from": "users",
//         "localField": "user_id",
//         "foreignField": "_id",
//         "as": "user"
//     }},
//     { "$addFields": { "user" : { "$first": "$__user" } } }
// ]
LoadRelation

Load related document using $lookup and $addField (Lookup and Unwrap method mix).

// Signature:
LoadRelation(from string, local string, foreign string, as string) MongoPipeline

// Example:
pipe.LoadRelation("users", "user_id", "_id", "user")
Group

Add $group stage.

// Signature:
Group(cb func(d MongoDoc) MongoDoc) MongoPipeline

// Example:
pipe.
    Group(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
        d.
            Add("_id", "$_id").
            Nested("name", "$first", "$name").
            Nested("total", "$sum", "$invoice")
        return d
    })
// -> [
//   { "$group": {
//       "_id": "$_id"
//       "name": { "$first": "$name" },
//       "total": { "$sum": "$invoice" }
//   }}
// ]
ReplaceRoot

Add $replaceRoot stage.

// Signature:
ReplaceRoot(v any) MongoPipeline

// Example:
pipe.ReplaceRoot("$my_root")
// ->  [{ "$replaceRoot": {"newRoot": "$my_root" } }]
MergeRoot

Add $replaceRoot stage with $mergeObjects operator.

// Signature:
MergeRoot(fields ...any) MongoPipeline

// Example:
pipe.MergeRoot("$my_root", "$$ROOT")
// -> [
//     {
//         "$replaceRoot": {
//             "newRoot": { "mergeObjects": ["$my_root", "$$ROOT"] }
//         }
//     }
// ]
UnProject

Generate $project stage to remove fields from result.

// Signature:
UnProject(fields ...string) MongoPipeline

// Example:
pipe.UnProject("my_root", "__user")
// -> [
//     { "$project": { "my_root": 0, "__user": 0 } }
// ]
Project

Generate $project stage. skip nil input.

// Signature:
Project(projects any) MongoPipeline

// Example:
pipe.Project(nil) // skiped
pipe.Project(primitve.M{"password": 0}) // remove password from result
Build

Generate mongo pipeline.

Build() mongo.Pipeline

MetaCounter

meta counter builder for mongo docs.

import "github.com/bopher/mongoutils"
mCounter := mongoutils.NewMetaCounter()
mCounter.Add("services", "relations", id1, 2)
mCounter.Add("services", "relations", id1, 1)
mCounter.Add("services", "total", id2, 1)
mCounter.Add("services", "total", id2, 1)
mCounter.Add("services", "relations", id3, 3)
mCounter.Add("services", "relations", nil, 3) // ignored
mCounter.Add("services", "relations", id3, -3) // ignored because of 0
mCounter.Add("customers", "rel", id1, 4)
mCounter.Add("customers", "rel", id2, 3)
mCounter.Add("customers", "rel", id2, 1)
mCounter.Add("customers", "rel", id3, 4)
fmt.Println(mCounter.Build())
// ->
// [
//   {
//     "Col": "services",
//     "Ids": ["62763152a01b7d275ef58e00"],
//     "Values": {
//       "relations": 3
//     }
//   },
//   {
//     "Col": "services",
//     "Ids": ["62763152a01b7d275ef58e01"],
//     "Values": {
//       "total": 2
//     }
//   },
//   {
//     "Col": "customers",
//     "Ids": [
//       "62763152a01b7d275ef58e00",
//       "62763152a01b7d275ef58e01",
//       "62763152a01b7d275ef58e02"
//     ],
//     "Values": {
//       "rel": 4
//     }
//   }
// ]

MetaSetter

meta setter builder for mongo docs.

import "github.com/bopher/mongoutils"
setter := mongoutils.NewMetaSetter()
setter.Add("test", "activity", id1, date)
setter.Add("test", "activity", nil, date) // ignored
setter.Add("test", "activity", id2, date)
setter.Add("test", "activity", id3, date) // override next line
setter.Add("test", "activity", id3, nil) // nil used
fmt.Println(setter.Build())
// ->
// [
//   {
//     "Col": "test",
//     "Ids": ["6276509942d11385d52b7ae2", "6276509942d11385d52b7ae3"],
//     "Values": {
//       "activity": "2022-05-07 10:57:29.6228877 +0000 UTC"
//     }
//   },
//   {
//     "Col": "test",
//     "Ids": ["6276509942d11385d52b7ae4"],
//     "Values": {
//       "activity": nil
//     }
//   },
// ]

Repository

Methods for work with data based on mongoutils.Model implementation!

You can define multiple Pipeline methods for your model and use them to fetch data by Pipeline option and params. If no pipeline option passed functions used Pipeline() method by default!

Find

Find find records.

// Signature
func Find[T any](
    filter any,
    sorts any,
    skip int64,
    limit int64,
    opts ...MongoOption,
) ([]T, error)

// Example
import "github.com/bopher/mongoutils"
type User struct{
    mongoutils.BaseModel `bson:",inline"`
    Name string `bson:"name" json:"name"`
}

func (*User) UserWithAccountPipe() mongoutils.MongoPipeline{
    // ...
}

users, err := mongoutils.Find[User](
    primitive.M{"name": "John"},
    primitive.M{"created_at": -1}, 0, 10,
    MongoOption{
        Debug: true,
        Pipeline: "UserWithAccountPipe",
        Params: []any{"1 June 1991", 12, 3},
    })
FindOne

Find one record.

// Signature
func FindOne[T any](
    filter any,
    sorts any,
    opts ...MongoOption,
) (*T, error)
Insert

Insert new record.

// Signature
func Insert[T any](
    v *T,
    opts ...MongoOption,
) (*mongo.InsertOneResult, error)
Update

Update one record.

// Signature
func Update[T any](
    v *T,
    silent bool,
    opts ...MongoOption,
) (*mongo.UpdateResult, error)
Delete

Delete one record.

// Signature
func Delete[T any](
    v *T,
    opts ...MongoOption,
) (*mongo.DeleteResult, error)
Count

Get records count.

// Signature
func Count[T any](
    filter any,
    opts ...MongoOption,
) (int64, error)
BatchUpdate

Update multiple records.

// Signature
func BatchUpdate[T any](
    condition any,
    updates any,
    opts ...MongoOption,
) (*mongo.UpdateResult, error)
Patch

Partial update multiple records using $set

// Signature
func Patch[T any](
    condition any,
    data primitive.M,
    silent bool,
    opts ...MongoOption,
) (*mongo.UpdateResult, error)
Increment

Increment numeric data. Pass negative value for decrement.

// Signature
func Increment[T any](
    condition any,
    data any,
    opts ...MongoOption,
) (*mongo.UpdateResult, error)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AggregateOption added in v1.1.0

func AggregateOption() *options.AggregateOptions

AggregateOption generate aggregation options

func Array added in v1.1.6

func Array(args ...any) primitive.A

Array generate primitive.A

func BatchUpdate added in v1.4.0

func BatchUpdate[T any](condition any, updates any, opts ...MongoOption) (*mongo.UpdateResult, error)

func BatchUpdateCtx added in v1.4.3

func BatchUpdateCtx[T any](
	ctx context.Context,
	condition any,
	updates any,
	opts ...MongoOption,
) (*mongo.UpdateResult, error)

BatchUpdate update multiple records

@param ctx operation context @param condition update condition @param updates update value @opts operation option

func Count added in v1.4.0

func Count[T any](filter any, opts ...MongoOption) (int64, error)

func CountCtx added in v1.4.3

func CountCtx[T any](
	ctx context.Context,
	filter any,
	opts ...MongoOption,
) (int64, error)

Count get records count

@param ctx operation context @param filter (ignored on nil) @opts operation option

func Delete added in v1.4.0

func Delete[T any](v *T, opts ...MongoOption) (*mongo.DeleteResult, error)

func DeleteCtx added in v1.4.3

func DeleteCtx[T any](
	ctx context.Context,
	v *T,
	opts ...MongoOption,
) (*mongo.DeleteResult, error)

Delete delete record

@param ctx operation context @param v model @opts operation option

func Doc added in v1.1.6

func Doc(args ...any) primitive.D

Doc generate primitive.D from args

Args count must even Example: Doc("_id", 1, "name", "John")

func Find added in v1.4.0

func Find[T any](filter any, sorts any, skip int64, limit int64, opts ...MongoOption) ([]T, error)

func FindCtx added in v1.4.3

func FindCtx[T any](
	ctx context.Context,
	filter any,
	sorts any,
	skip int64,
	limit int64,
	opts ...MongoOption,
) ([]T, error)

Find find records

@param ctx operation context @param filter (ignored on nil) @param sorts (ignored on nil) @param skip (ignored on 0) @param limit (ignored on 0) @opts operation option

func FindOne added in v1.4.0

func FindOne[T any](filter any, sorts any, opts ...MongoOption) (*T, error)

func FindOneCtx added in v1.4.3

func FindOneCtx[T any](
	ctx context.Context,
	filter any,
	sorts any,
	opts ...MongoOption,
) (*T, error)

FindOne find one record

@param ctx operation context @param filter (ignored on nil) @param sorts (ignored on nil) @opts operation option

func FindOption added in v1.1.0

func FindOption(sort any, skip int64, limit int64) *options.FindOptions

FindOption generate find option with sorts params

func In added in v1.1.0

func In(k string, v ...any) primitive.M

In generate $in map

{k: {$in: v}}

func Increment added in v1.4.0

func Increment[T any](condition any, data any, opts ...MongoOption) (*mongo.UpdateResult, error)

func IncrementCtx added in v1.4.3

func IncrementCtx[T any](
	ctx context.Context,
	condition any,
	data any,
	opts ...MongoOption,
) (*mongo.UpdateResult, error)

Increment increment numeric data pass negative value for decrement increment run on silent mode

@param ctx operation context @param condition update condition @param data update value @opts operation option

func Insert added in v1.4.0

func Insert[T any](v *T, opts ...MongoOption) (*mongo.InsertOneResult, error)

func InsertCtx added in v1.4.3

func InsertCtx[T any](
	ctx context.Context,
	v *T,
	opts ...MongoOption,
) (*mongo.InsertOneResult, error)

Insert insert new record this function use FindOne to find old record

@param ctx operation context @param v model @opts operation option

func IsValidObjectId

func IsValidObjectId(id *primitive.ObjectID) bool

IsValidObjectId check if object id is valid and not zero

func Map added in v1.1.6

func Map(args ...any) primitive.M

Map generate primitive.M

Args count must even

func Maps added in v1.1.6

func Maps(args ...any) []primitive.M

Maps generate []primitive.M

Args count must even

func Match added in v1.1.0

func Match(v any) primitive.M

Match generate nested set map

{$match: v}

func MongoOperationCtx added in v1.4.0

func MongoOperationCtx() (context.Context, context.CancelFunc)

MongoOperationCtx create context for mongo db operations for 10 sec

func ParseObjectID

func ParseObjectID(id string) *primitive.ObjectID

ParseObjectID parse object id from string

func Patch added in v1.4.0

func Patch[T any](condition any, data primitive.M, silent bool, opts ...MongoOption) (*mongo.UpdateResult, error)

func PatchCtx added in v1.4.3

func PatchCtx[T any](
	ctx context.Context,
	condition any,
	data primitive.M,
	silent bool,
	opts ...MongoOption,
) (*mongo.UpdateResult, error)

Patch partial update multiple records using $set

@param ctx operation context @param condition update condition @param data update value @param silent disable update meta (updated_at) @opts operation option

func Regex added in v1.1.2

func Regex(pattern string, opt string) primitive.Regex

Regex generate Regex

{ pattern: "John.*", options: "i" }

func RegexFor added in v1.1.6

func RegexFor(k string, pattern string, opt string) primitive.M

RegexFor generate map with regex parameter

{ "name": { pattern: "John.*", options: "i" } }

func Set added in v1.1.0

func Set(v any) primitive.M

Set generate simple set map

{$set: v}

func SetNested added in v1.1.0

func SetNested(k string, v any) primitive.M

SetNested generate nested set map

{$set: {k: v}}

func TxOption added in v1.1.8

func TxOption() *options.TransactionOptions

TxOption generate transaction option with majority write and snapshot read

func Update added in v1.4.0

func Update[T any](v *T, silent bool, opts ...MongoOption) (*mongo.UpdateResult, error)

func UpdateCtx added in v1.4.3

func UpdateCtx[T any](
	ctx context.Context,
	v *T,
	silent bool,
	opts ...MongoOption,
) (*mongo.UpdateResult, error)

Update update one record

@param ctx operation context @param v model @param silent disable update meta (updated_at) @opts operation option

Types

type BaseModel added in v1.3.0

type BaseModel struct {
	ID        primitive.ObjectID `bson:"_id,omitempty" json:"_id"`
	CreatedAt time.Time          `bson:"created_at" json:"created_at"`
	UpdatedAt *time.Time         `bson:"updated_at" json:"updated_at"`
}

BaseModel implementation with id and timestamp

func (*BaseModel) Cleanup added in v1.3.0

func (*BaseModel) Cleanup()

func (*BaseModel) Collection added in v1.3.0

func (*BaseModel) Collection(db *mongo.Database) *mongo.Collection

func (*BaseModel) GetID added in v1.3.2

func (model *BaseModel) GetID() primitive.ObjectID

func (*BaseModel) Index added in v1.4.7

func (*BaseModel) Index(db *mongo.Database) error

func (*BaseModel) IsDeletable added in v1.3.0

func (*BaseModel) IsDeletable() bool

func (*BaseModel) IsEditable added in v1.3.0

func (*BaseModel) IsEditable() bool

func (*BaseModel) NewId added in v1.3.0

func (model *BaseModel) NewId()

func (*BaseModel) OnDelete added in v1.3.0

func (*BaseModel) OnDelete(ctx context.Context, opt ...MongoOption)

func (*BaseModel) OnDeleted added in v1.3.0

func (*BaseModel) OnDeleted(ctx context.Context, opt ...MongoOption)

func (*BaseModel) OnInsert added in v1.3.0

func (*BaseModel) OnInsert(ctx context.Context, opt ...MongoOption)

func (*BaseModel) OnInserted added in v1.3.0

func (*BaseModel) OnInserted(ctx context.Context, opt ...MongoOption)

func (*BaseModel) OnUpdate added in v1.3.0

func (*BaseModel) OnUpdate(ctx context.Context, opt ...MongoOption)

func (*BaseModel) OnUpdated added in v1.3.0

func (*BaseModel) OnUpdated(old any, ctx context.Context, opt ...MongoOption)

func (*BaseModel) Pipeline added in v1.3.0

func (*BaseModel) Pipeline() MongoPipeline

func (*BaseModel) PrepareInsert added in v1.3.0

func (model *BaseModel) PrepareInsert()

func (*BaseModel) PrepareUpdate added in v1.3.0

func (model *BaseModel) PrepareUpdate(ghost bool)

func (*BaseModel) Seed added in v1.4.0

func (*BaseModel) Seed(db *mongo.Database) error

func (*BaseModel) SetID added in v1.3.0

func (model *BaseModel) SetID(id primitive.ObjectID)

func (*BaseModel) TypeName added in v1.3.6

func (*BaseModel) TypeName() string

type EmptyModel added in v1.3.1

type EmptyModel struct{}

EmptyModel only implement model methods

func (*EmptyModel) Cleanup added in v1.3.1

func (*EmptyModel) Cleanup()

func (*EmptyModel) Collection added in v1.3.1

func (*EmptyModel) Collection(db *mongo.Database) *mongo.Collection

func (*EmptyModel) GetID added in v1.3.2

func (*EmptyModel) GetID() primitive.ObjectID

func (*EmptyModel) Index added in v1.4.7

func (*EmptyModel) Index(db *mongo.Database) error

func (*EmptyModel) IsDeletable added in v1.3.1

func (*EmptyModel) IsDeletable() bool

func (*EmptyModel) IsEditable added in v1.3.1

func (*EmptyModel) IsEditable() bool

func (*EmptyModel) NewId added in v1.3.1

func (*EmptyModel) NewId()

func (*EmptyModel) OnDelete added in v1.3.1

func (*EmptyModel) OnDelete(ctx context.Context, opt ...MongoOption)

func (*EmptyModel) OnDeleted added in v1.3.1

func (*EmptyModel) OnDeleted(ctx context.Context, opt ...MongoOption)

func (*EmptyModel) OnInsert added in v1.3.1

func (*EmptyModel) OnInsert(ctx context.Context, opt ...MongoOption)

func (*EmptyModel) OnInserted added in v1.3.1

func (*EmptyModel) OnInserted(ctx context.Context, opt ...MongoOption)

func (*EmptyModel) OnUpdate added in v1.3.1

func (*EmptyModel) OnUpdate(ctx context.Context, opt ...MongoOption)

func (*EmptyModel) OnUpdated added in v1.3.1

func (*EmptyModel) OnUpdated(old any, ctx context.Context, opt ...MongoOption)

func (*EmptyModel) Pipeline added in v1.3.1

func (*EmptyModel) Pipeline() MongoPipeline

func (*EmptyModel) PrepareInsert added in v1.3.1

func (*EmptyModel) PrepareInsert()

func (*EmptyModel) PrepareUpdate added in v1.3.1

func (*EmptyModel) PrepareUpdate(ghost bool)

func (*EmptyModel) Seed added in v1.4.1

func (*EmptyModel) Seed(db *mongo.Database) error

func (*EmptyModel) SetID added in v1.3.1

func (*EmptyModel) SetID(id primitive.ObjectID)

func (*EmptyModel) TypeName added in v1.3.6

func (*EmptyModel) TypeName() string

type IrCity added in v1.5.1

type IrCity struct {
	EmptyModel `bson:"inline"`
	ID         primitive.ObjectID  `bson:"_id" json:"_id"`
	Code       uint                `bson:"code" json:"code"`
	Name       string              `bson:"name" json:"name"`
	CountyId   *primitive.ObjectID `bson:"county_id" json:"county_id"`
	ProvinceId *primitive.ObjectID `bson:"province_id" json:"province_id"`
	County     *IrCity             `bson:"county,omitempty" json:"county"`
	Province   *IrCity             `bson:"province,omitempty" json:"province"`
}

IrCity only implement model methods

func (*IrCity) Cleanup added in v1.5.1

func (ic *IrCity) Cleanup()

func (*IrCity) Collection added in v1.5.1

func (*IrCity) Collection(db *mongo.Database) *mongo.Collection

func (*IrCity) GetID added in v1.5.1

func (ic *IrCity) GetID() primitive.ObjectID

func (*IrCity) Index added in v1.5.1

func (ic *IrCity) Index(db *mongo.Database) error

func (*IrCity) IsEditable added in v1.5.1

func (*IrCity) IsEditable() bool

func (*IrCity) NewId added in v1.5.1

func (ic *IrCity) NewId()

func (*IrCity) Seed added in v1.5.1

func (i *IrCity) Seed(db *mongo.Database) error

func (*IrCity) SetID added in v1.5.1

func (ic *IrCity) SetID(id primitive.ObjectID)

func (*IrCity) SinglePipeline added in v1.5.1

func (*IrCity) SinglePipeline() MongoPipeline

func (*IrCity) TypeName added in v1.5.1

func (*IrCity) TypeName() string

type MetaCounter added in v1.2.4

type MetaCounter interface {
	// Add new meta
	Add(_col, _meta string, id *primitive.ObjectID, amount int) MetaCounter
	// Build get combined meta with query
	Build() []MetaCounterResult
}

func NewMetaCounter added in v1.2.0

func NewMetaCounter() MetaCounter

NewMetaCounter new mongo meta counter

type MetaCounterResult added in v1.2.4

type MetaCounterResult struct {
	Col string
	Ids []primitive.ObjectID
	// data to update
	Values map[string]int
}

type MetaSetter added in v1.2.4

type MetaSetter interface {
	// Add new meta
	Add(_col, _meta string, id *primitive.ObjectID, value any) MetaSetter
	// Build get combined meta with query
	Build() []MetaSetterResult
}

func NewMetaSetter added in v1.2.4

func NewMetaSetter() MetaSetter

NewMetaSetter new mongo meta setter

type MetaSetterResult added in v1.2.4

type MetaSetterResult struct {
	Col    string
	Ids    []primitive.ObjectID
	Values map[string]any
}

type Model added in v1.1.0

type Model interface {
	// TypeName get type string
	TypeName() string
	// Collection get model collection
	Collection(db *mongo.Database) *mongo.Collection
	// Indexes create model indexes
	Index(db *mongo.Database) error
	// Seed run model seed
	Seed(db *mongo.Database) error
	// Pipeline get model pipeline
	Pipeline() MongoPipeline
	// NewId generate new id for model
	NewId()
	// SetID set model id
	SetID(id primitive.ObjectID)
	// ID get model id
	GetID() primitive.ObjectID
	// IsEditable check if document is editable
	// by default returns true on BaseModel
	IsEditable() bool
	// IsDeletable check if document is deletable
	// by default returns false on BaseModel
	IsDeletable() bool
	// Cleanup document before save
	// e.g set document field nil for ignore saving
	Cleanup()
	// PrepareInsert fill created_at before save
	PrepareInsert()
	// PrepareUpdate fill updated_at before save
	// in ghost mode updated_at field not changed
	PrepareUpdate(ghost bool)
	// OnInsert function to call before insert
	OnInsert(ctx context.Context, opt ...MongoOption)
	// OnUpdate function to call before update
	OnUpdate(ctx context.Context, opt ...MongoOption)
	// OnDelete function to call before delete
	OnDelete(ctx context.Context, opt ...MongoOption)
	// OnInserted function to call after insert
	OnInserted(ctx context.Context, opt ...MongoOption)
	// OnUpdated function to call after update
	OnUpdated(old any, ctx context.Context, opt ...MongoOption)
	// OnDeleted function to call after delete
	OnDeleted(ctx context.Context, opt ...MongoOption)
}

model interface

type MongoDoc

type MongoDoc interface {
	// Add add new element
	Add(k string, v any) MongoDoc
	// Doc add new element with nested doc value
	Doc(k string, cb func(d MongoDoc) MongoDoc) MongoDoc
	// Array add new element with array value
	Array(k string, v ...any) MongoDoc
	// DocArray add new array element with doc
	DocArray(k string, cb func(d MongoDoc) MongoDoc) MongoDoc
	// Nested add new nested element
	Nested(root string, k string, v any) MongoDoc
	// NestedDoc add new nested element with doc value
	NestedDoc(root string, k string, cb func(d MongoDoc) MongoDoc) MongoDoc
	// NestedArray add new nested element with array value
	NestedArray(root string, k string, v ...any) MongoDoc
	// NestedDocArray add new nested array element with doc
	NestedDocArray(root string, k string, cb func(d MongoDoc) MongoDoc) MongoDoc
	// Regex add new element with regex value
	Regex(k string, pattern string, opt string) MongoDoc
	// Map creates a map from the elements of the Doc
	Map() primitive.M
	// Build generate mongo doc
	Build() primitive.D
}

MongoDoc mongo document (primitive.D) builder

func NewDoc

func NewDoc() MongoDoc

NewDoc new mongo doc builder

type MongoOption added in v1.4.0

type MongoOption struct {
	DebugPipe   bool
	DebugResult bool
	Pipeline    string
	Params      []any
	Database    *mongo.Database
}

type MongoPipeline

type MongoPipeline interface {
	// Add add new Doc
	Add(cb func(d MongoDoc) MongoDoc) MongoPipeline
	// Match add $match stage. skip nil input
	Match(filters any) MongoPipeline
	// In add $in stage
	In(key string, v any) MongoPipeline
	// Limit add $limit stage (ignore negative and zero value)
	Limit(limit int64) MongoPipeline
	// Skip add $skip stage (ignore negative and zero value)
	Skip(skip int64) MongoPipeline
	// Sort add $sort stage (ignore nil value)
	Sort(sorts any) MongoPipeline
	// Unwind add $unwind stage
	Unwind(path string, prevNullAndEmpty bool) MongoPipeline
	// Lookup add $lookup stage
	Lookup(from string, local string, foreign string, as string) MongoPipeline
	// Unwrap get first item of array and insert to doc using $addFields stage
	Unwrap(field string, as string) MongoPipeline
	// LoadRelation load related document using $lookup and $addField
	LoadRelation(from string, local string, foreign string, as string) MongoPipeline
	// Group add $group stage
	Group(cb func(d MongoDoc) MongoDoc) MongoPipeline
	// ReplaceRoot add $replaceRoot stage
	ReplaceRoot(v any) MongoPipeline
	// MergeRoot add $replaceRoot stage with $mergeObjects operator
	MergeRoot(fields ...any) MongoPipeline
	// UnProject generate $project stage to remove fields from result
	UnProject(fields ...string) MongoPipeline
	// Project add $project stage. skip nil input
	Project(projects any) MongoPipeline
	// Build generate mongo pipeline
	Build() mongo.Pipeline
}

MongoPipeline mongo pipeline (mongo.Pipeline) builder

func NewPipe

func NewPipe() MongoPipeline

NewPipe new mongo pipe builder

Jump to

Keyboard shortcuts

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