mongoutils

package module
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2022 License: MIT Imports: 7 Imported by: 0

README

MongoUtils

Mongodb helper functions, document and pipeline builder.

Helpers

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: Implement (Pointer) methods in pointer mode. e.g. func (p *Person) OnInsert(ctx context.Context){}

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

// Collection get model collection
Collection() *mongo.Collection
// Indexes get model indexes
Indexes() []mongo.IndexModel
// 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)
// OnUpdate function to call before update (Pointer)
OnUpdate(ctx context.Context)
// OnDelete function to call before delete (Pointer)
OnDelete(ctx context.Context)
// OnInserted function to call after insert
OnInserted(ctx context.Context)
// OnUpdated function to call after update
OnUpdated(old any, ctx context.Context)
// OnDeleted function to call after delete
OnDeleted(ctx context.Context)
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
//     }
//   },
// ]

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 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 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 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 ParseObjectID

func ParseObjectID(id string) *primitive.ObjectID

ParseObjectID parse object id from string

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

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() *mongo.Collection

func (BaseModel) GetID added in v1.3.2

func (model BaseModel) GetID() primitive.ObjectID

func (BaseModel) Indexes added in v1.3.3

func (BaseModel) Indexes() []mongo.IndexModel

Indexes get model indexes

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)

func (BaseModel) OnDeleted added in v1.3.0

func (BaseModel) OnDeleted(ctx context.Context)

func (*BaseModel) OnInsert added in v1.3.0

func (*BaseModel) OnInsert(ctx context.Context)

func (BaseModel) OnInserted added in v1.3.0

func (BaseModel) OnInserted(ctx context.Context)

func (*BaseModel) OnUpdate added in v1.3.0

func (*BaseModel) OnUpdate(ctx context.Context)

func (BaseModel) OnUpdated added in v1.3.0

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

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) SetID added in v1.3.0

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

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() *mongo.Collection

func (EmptyModel) GetID added in v1.3.2

func (EmptyModel) GetID() primitive.ObjectID

func (EmptyModel) Indexes added in v1.3.3

func (EmptyModel) Indexes() []mongo.IndexModel

Indexes get model indexes

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)

func (EmptyModel) OnDeleted added in v1.3.1

func (EmptyModel) OnDeleted(ctx context.Context)

func (*EmptyModel) OnInsert added in v1.3.1

func (*EmptyModel) OnInsert(ctx context.Context)

func (EmptyModel) OnInserted added in v1.3.1

func (EmptyModel) OnInserted(ctx context.Context)

func (*EmptyModel) OnUpdate added in v1.3.1

func (*EmptyModel) OnUpdate(ctx context.Context)

func (EmptyModel) OnUpdated added in v1.3.1

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

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) SetID added in v1.3.1

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

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 {
	// Collection get model collection
	Collection() *mongo.Collection
	// Indexes get model indexes
	Indexes() []mongo.IndexModel
	// Pipeline get model pipeline
	Pipeline() MongoPipeline
	// NewId generate new id for model (Pointer)
	NewId()
	// SetID set model id (Pointer)
	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 (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)
	// OnUpdate function to call before update (Pointer)
	OnUpdate(ctx context.Context)
	// OnDelete function to call before delete (Pointer)
	OnDelete(ctx context.Context)
	// OnInserted function to call after insert
	OnInserted(ctx context.Context)
	// OnUpdated function to call after update
	OnUpdated(old any, ctx context.Context)
	// OnDeleted function to call after delete
	OnDeleted(ctx context.Context)
}

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 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