mongorm

package module
v1.0.26 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

README

MongORM

MongORM is a production-ready, type-safe MongoDB ORM for Go that combines generics, fluent query building, and predictable data modeling. It helps Go teams ship faster with clean CRUD workflows, typed filters, aggregation support, and transaction-safe operations.

If you are building backend APIs, SaaS products, internal tools, or data-heavy services on MongoDB, MongORM gives you a high-signal developer experience without hiding core MongoDB power.

Developer information

Open source by Azayn Labs

Home: azayn.com | LinkedIn: linkedin.com/company/azayn-labs

GitHub Profile: github.com/azayn-labs

GitHub Project: MongORM

Features

  • Type-safe model and schema definitions using Go generics
  • Fluent API for building queries with Where(), OrWhere(), Sort(), Limit(), Skip(), Projection(), keyset pagination helpers, Set(), SetOnInsert(), and Unset()
  • Typed projection decoding for DTO targets via FindOneAs[T, R]() and FindAllAs[T, R]()
  • Full CRUD support: create, find, update (single and multi), and delete (single and multi)
  • Bulk write support with typed builder helpers via BulkWrite(), BulkWriteInTransaction(), and NewBulkWriteBuilder[T]()
  • Aggregation support: raw pipelines and fluent stage builder via Aggregate(), AggregateRaw(), AggregateAs[T, R](), and AggregatePipeline()
  • Query utilities: Count(), Distinct(), DistinctFieldAs[T, V](), DistinctStrings(), DistinctInt64(), DistinctBool(), DistinctFloat64(), DistinctObjectIDs(), and DistinctTimes()
  • Geospatial support: GeoField with Near, Within, and Intersects query helpers
  • Index support: field-driven builders, Ensure2DSphereIndex(), and EnsureGeoDefaults()
  • Transactions: WithTransaction() for atomic multi-operation workflows
  • Optimistic locking via mongorm:"version" (_version) and ErrOptimisticLockConflict
  • Error taxonomy with sentinels: ErrNotFound, ErrDuplicateKey, ErrInvalidConfig, ErrTransactionUnsupported
  • Lifecycle hooks for every operation (Before/After Create, Save, Update, Find, Delete, Finalize)
  • Automatic CreatedAt / UpdatedAt timestamp management
  • Flexible configuration: struct tags, options struct, or both
  • Cursor-based iteration for large result sets
  • Connection pooling — clients are reused by connection string
  • Lightweight with a single dependency: the official MongoDB Go driver

Why teams choose MongORM

  • Type-safe by default: schema primitives and generics reduce runtime query mistakes.
  • Fast developer velocity: fluent APIs for filtering, updates, aggregation, and bulk workflows.
  • Production-focused reliability: transactions, optimistic locking, timestamps, hooks, and clear error taxonomy.
  • MongoDB-native flexibility: raw BSON compatibility when you need full control.
  • Clean architecture fit: works naturally with service layers, repository patterns, and domain models.

Installation

go get github.com/azayn-labs/mongorm

Quick Start

package main

import (
    "context"
    "fmt"

    "github.com/azayn-labs/mongorm"
    "github.com/azayn-labs/mongorm/primitives"
    "go.mongodb.org/mongo-driver/v2/bson"
)

type ToDo struct {
    ID   *bson.ObjectID `bson:"_id,omitempty" mongorm:"primary"`
    Text *string        `bson:"text,omitempty"`

    // Connection embedded in struct tags
    connectionString *string `mongorm:"mongodb://localhost:27017,connection:url"`
    database         *string `mongorm:"mydb,connection:database"`
    collection       *string `mongorm:"todos,connection:collection"`
}

type ToDoSchema struct {
    ID   *primitives.ObjectIDField
    Text *primitives.StringField
}

var ToDoFields = mongorm.FieldsOf[ToDo, ToDoSchema]()

func main() {
    ctx := context.Background()

    // Create
    todo := &ToDo{Text: mongorm.String("Buy groceries")}
    orm  := mongorm.New(todo)
    if err := orm.Save(ctx); err != nil {
        panic(err)
    }
    fmt.Printf("Created: %s\n", todo.ID.Hex())

    // Find by ID
    found := &ToDo{}
    mongorm.New(found).Where(ToDoFields.ID.Eq(*todo.ID)).First(ctx)
    fmt.Printf("Found: %s\n", *found.Text)

    // Update
    mongorm.New(&ToDo{}).
        Where(ToDoFields.ID.Eq(*todo.ID)).
        Set(&ToDo{Text: mongorm.String("Buy organic groceries")}).
        Save(ctx)

    // OR filtering
    cursor, err := mongorm.New(&ToDo{}).
        OrWhere(ToDoFields.Text.Eq("Buy groceries")).
        OrWhereBy(ToDoFields.Text, "Buy organic groceries").
        FindAll(ctx)
    if err != nil {
        panic(err)
    }
    defer cursor.Close(ctx)

    // Delete
    mongorm.New(&ToDo{}).Where(ToDoFields.ID.Eq(*todo.ID)).Delete(ctx)
}

Documentation

Full documentation is in the docs/ folder.

Topic Description
Getting Started Installation, model definition, schema setup
Configuration Struct tags, options struct, mixed mode
Creating Documents Inserting with Save()
Finding Documents Querying with First() / Find(), Count(), and Distinct()
Updating Documents Single and bulk updates
Deleting Documents Removing documents
Bulk Write Batch insert/update/replace/delete operations
Indexes Field-based index builders and geo index setup
Aggregation Aggregation pipelines with fluent builder and typed decoding
Cursors Iterating with FindAll()
Query Building Where(), OrWhere(), find modifiers, pagination helpers, Set(), SetOnInsert(), Unset()
Primitives Type-safe field query methods
Hooks Lifecycle hooks
Transactions Running operations in MongoDB transactions
Errors Sentinel errors and handling patterns
Timestamps Automatic CreatedAt / UpdatedAt
Utility Types Pointer helpers

API Quick Reference

Quick map of commonly used entry points and where they are documented:

  • Core initialization: New(), FromOptions(), NewClient()Configuration
  • CRUD execution: Save(), FindOneAndUpdate(), SaveMulti(), Delete(), DeleteMulti(), First() / Find()Creating Documents, Finding Documents, Updating Documents, Deleting Documents
  • Query builders: Where(), WhereBy(), OrWhere(), OrWhereBy(), Sort(), Limit(), Skip(), Projection(), After() / Before(), PaginateAfter() / PaginateBefore(), Set(), SetOnInsert(), Unset()Query Building
  • Typed read helpers: FindOneAs[T, R](), FindAllAs[T, R]()Finding Documents
  • Distinct and count: Count(), Distinct(), DistinctFieldAs[T, V](), DistinctStrings(), DistinctInt64(), DistinctBool(), DistinctFloat64(), DistinctObjectIDs(), DistinctTimes()Finding Documents
  • Aggregation: Aggregate(), AggregateRaw(), AggregateAs[T, R](), AggregatePipelineAs[T, R]() plus stage builders → Aggregation
  • Bulk and indexes: NewBulkWriteBuilder[T](), BulkWrite(), BulkWriteInTransaction(), EnsureIndex*() helpers → Bulk Write, Indexes
  • Cursors and output: FindAll(), MongORMCursor.Next(), MongORMCursor.All(), Document(), JSON()Cursors, Utility Types
  • Transactions and errors: WithTransaction(), IsTransactionUnsupported(), sentinel errors (ErrNotFound, ErrDuplicateKey, ErrInvalidConfig, ErrTransactionUnsupported, ErrOptimisticLockConflict) → Transactions, Errors

HTML documentation is available at html_docs/index.html.

Keywords

Go MongoDB ORM, Golang MongoDB ORM, type-safe MongoDB query builder for Go, Go generics ORM, MongoDB CRUD library for Go, MongoDB transactions in Go, MongoDB aggregation in Go, MongoDB bulk write Go, MongoDB hooks and timestamps, lightweight Go ORM.

GitHub SEO Pack

Use these when publishing the repository to maximize discoverability in GitHub search and community feeds.

Repository Description (pick one)
  • Production-ready, type-safe MongoDB ORM for Go with generics, fluent query building, transactions, aggregation, and bulk operations.
  • Type-safe MongoDB ORM for Go: fluent CRUD, typed filters, aggregation pipelines, bulk writes, hooks, and transaction support.
  • Lightweight Golang MongoDB ORM with generics, query builder, optimistic locking, timestamps, and production-friendly data workflows.
Suggested GitHub Topics

go, golang, mongodb, orm, mongo-orm, golang-library, backend, query-builder, type-safe, generics, aggregation, transactions, bulk-write, developer-tools, data-access

Launch Checklist
  • Set repository description using one of the options above.
  • Add the suggested topic tags in GitHub repository settings.
  • Publish v1.0.0 as the first stable release using .github/RELEASE_TEMPLATE.md.
  • Pin a concise usage example in the release body (create + find + update).
  • Share release in Go and MongoDB communities with keywords from this README.

Geo Index Defaults Example

ctx := context.Background()

err := mongorm.New(&ToDo{}).EnsureGeoDefaults(
    ctx,
    ToDoFields.Location,
    []bson.E{mongorm.Asc(ToDoFields.CreatedAt)},
)
if err != nil {
    panic(err)
}

License

See LICENSE.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound               = errors.New("mongorm: not found")
	ErrDuplicateKey           = errors.New("mongorm: duplicate key")
	ErrInvalidConfig          = errors.New("mongorm: invalid configuration")
	ErrTransactionUnsupported = errors.New("mongorm: transaction unsupported")
	ErrOptimisticLockConflict = errors.New("mongorm: optimistic lock conflict")
)

Functions

func AddToSetUpdateFromPairs added in v1.0.8

func AddToSetUpdateFromPairs(pairs ...FieldValuePair) bson.M

AddToSetUpdateFromPairs builds an update document with $addToSet using schema fields.

func AggregateAs

func AggregateAs[T any, R any](
	m *MongORM[T],
	ctx context.Context,
	pipeline bson.A,
	opts ...options.Lister[options.AggregateOptions],
) ([]R, error)

AggregateAs runs an aggregation pipeline and decodes the results into a typed slice.

func AggregatePipelineAs

func AggregatePipelineAs[T any, R any](
	m *MongORM[T],
	ctx context.Context,
	opts ...options.Lister[options.AggregateOptions],
) ([]R, error)

AggregatePipelineAs decodes results from accumulated fluent pipeline stages into a typed slice.

func Asc

func Asc(field Field) bson.E

Asc returns an ascending index key for the given field.

func Bool

func Bool(b bool) *bool

Similar utility functions for other basic types (e.g., int, bool) can be defined in the same way.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
  Done *bool   `bson:"done"`
}
todo := &ToDo{
    Text: mongorm.String("Buy milk"),
    Done: mongorm.Bool(false),
}

func BoolVal

func BoolVal(b *bool) bool

BoolVal retrieves the value from a pointer to a bool. If the pointer is nil, it returns false. This function is useful for safely accessing the value of optional bool fields in the schema without having to check for nil pointers every time.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
  Done *bool   `bson:"done"`
}
todo := &ToDo{
    Text: mongorm.String("Buy milk"),
    Done: mongorm.Bool(false),
}
doneValue := mongorm.BoolVal(todo.Done) // doneValue will be false

func Decimal128 added in v1.0.24

func Decimal128(d bson.Decimal128) *bson.Decimal128

Decimal128 creates a pointer to a bson.Decimal128 value.

func Decimal128Val added in v1.0.24

func Decimal128Val(d *bson.Decimal128) bson.Decimal128

Decimal128Val retrieves the value from a pointer to a bson.Decimal128. If the pointer is nil, it returns the zero value of bson.Decimal128.

func Desc

func Desc(field Field) bson.E

Desc returns a descending index key for the given field.

func DistinctAs

func DistinctAs[V any](values []any) ([]V, error)

DistinctAs converts raw distinct values into a typed slice.

func DistinctFieldAs

func DistinctFieldAs[T any, V any](
	m *MongORM[T],
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]V, error)

DistinctFieldAs returns distinct values cast/converted to the requested type.

func Facet

func Facet(alias AggregateAlias, pipeline bson.A) bson.E

Facet creates a facet entry for FacetStageEntries.

func FieldRef

func FieldRef(field Field) string

FieldRef converts a Field to an aggregation field reference (e.g. "$count").

func FieldsOf

func FieldsOf[T any, F any]() F

Generates a struct of Field objects corresponding to the fields of the struct type T. This is used to create a schema struct that can be used for type-safe queries and updates.

Example usage:

	type ToDo struct {
	  Text *string `bson:"text"`
	}
	type ToDoSchema struct {
	  Text *primitives.StringField
	}
 var ToDoFields = mongorm.FieldsOf[ToDo, ToDoSchema]()

func FilterBy added in v1.0.3

func FilterBy(field Field, value any) bson.M

FilterBy creates an equality filter using a schema field.

func FindAllAs

func FindAllAs[T any, R any](
	m *MongORM[T],
	ctx context.Context,
	opts ...options.Lister[options.FindOptions],
) ([]R, error)

FindAllAs finds documents and decodes them into a projection DTO slice.

func FindOneAs

func FindOneAs[T any, R any](
	m *MongORM[T],
	ctx context.Context,
	opts ...options.Lister[options.FindOneOptions],
) (*R, error)

FindOneAs finds a single document and decodes it into a projection DTO type.

func Float64 added in v1.0.24

func Float64(f float64) *float64

Float64 creates a pointer to a float64 value. This function is useful for creating pointers to float values when defining schema structs for a MongORM instance.

Example usage:

type Product struct {
  Price *float64 `bson:"price"`
}
product := &Product{Price: mongorm.Float64(19.99)}

func Float64Val added in v1.0.24

func Float64Val(f *float64) float64

Float64Val retrieves the value from a pointer to a float64. If the pointer is nil, it returns 0. This function is useful for safely accessing optional float64 fields.

Example usage:

type Product struct {
  Price *float64 `bson:"price"`
}
product := &Product{Price: mongorm.Float64(19.99)}
priceValue := mongorm.Float64Val(product.Price) // priceValue will be 19.99

func Geo2D

func Geo2D(field Field) bson.E

Geo2D returns a 2d index key for the given field.

func Geo2DSphere

func Geo2DSphere(field Field) bson.E

Geo2DSphere returns a 2dsphere index key for the given field.

func IncUpdateFromPairs added in v1.0.7

func IncUpdateFromPairs(pairs ...FieldValuePair) bson.M

IncUpdateFromPairs builds an update document with $inc using schema fields.

func IndexModelFromKeys

func IndexModelFromKeys(keys ...bson.E) mongo.IndexModel

IndexModelFromKeys builds an index model from field-based keys.

func Int64

func Int64(i int64) *int64

Similar utility functions for other basic types (e.g., int, uint) can be defined in the same way.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
  Done *bool   `bson:"done"`
  Priority *int64 `bson:"priority"`
}
todo := &ToDo{
    Text: mongorm.String("Buy milk"),
    Done: mongorm.Bool(false),
    Priority: mongorm.Int64(1),
}

func Int64Val

func Int64Val(i *int64) int64

Int64Val retrieves the value from a pointer to an int64. If the pointer is nil, it returns 0. This function is useful for safely accessing the value of optional int64 fields in the schema without having to check for nil pointers every time.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
  Done *bool   `bson:"done"`
  Priority *int64 `bson:"priority"`
}
todo := &ToDo{
    Text: mongorm.String("Buy milk"),
    Done: mongorm.Bool(false),
    Priority: mongorm.Int64(1),
}
priorityValue := mongorm.Int64Val(todo.Priority) // priorityValue will be 1

func IsTransactionUnsupported

func IsTransactionUnsupported(err error) bool

func NamedIndexModelFromKeys

func NamedIndexModelFromKeys(name string, keys ...bson.E) mongo.IndexModel

NamedIndexModelFromKeys builds a named index model from field-based keys.

func NestedFieldsOf added in v1.0.3

func NestedFieldsOf[T any, F any](parent Field) F

Generates nested fields for a struct type T under a parent field path. This is useful for user-defined struct fields mapped as GenericField where deep, typed primitives are still desired.

Example:

type Profile struct {
  Provider *string `bson:"provider,omitempty"`
}
type ProfileSchema struct {
  Provider *primitives.StringField
}
var UserFields = mongorm.FieldsOf[User, UserSchema]()
var ProfileFields = mongorm.NestedFieldsOf[Profile, ProfileSchema](UserFields.Goth)

func NewClient

func NewClient(connectionString string) (*mongo.Client, error)

func PopUpdateFromPairs added in v1.0.8

func PopUpdateFromPairs(pairs ...FieldValuePair) bson.M

PopUpdateFromPairs builds an update document with $pop using schema fields.

func PullUpdateFromPairs added in v1.0.8

func PullUpdateFromPairs(pairs ...FieldValuePair) bson.M

PullUpdateFromPairs builds an update document with $pull using schema fields.

func PushUpdateFromPairs added in v1.0.8

func PushUpdateFromPairs(pairs ...FieldValuePair) bson.M

PushUpdateFromPairs builds an update document with $push using schema fields.

func SetOnInsertUpdateFromPairs added in v1.0.23

func SetOnInsertUpdateFromPairs(pairs ...FieldValuePair) bson.M

SetOnInsertUpdateFromPairs builds an update document with $setOnInsert using schema fields.

func SetUpdateFromPairs added in v1.0.3

func SetUpdateFromPairs(pairs ...FieldValuePair) bson.M

SetUpdateFromPairs builds an update document with $set using schema fields.

func String

func String(s string) *string

Utility functions for working with pointers to basic types. These functions are used to create pointers to values of basic types (e.g., string, int, bool) and to retrieve the values from pointers, providing a convenient way to work with optional fields in the schema. These functions are commonly used when defining the schema struct for a MongORM instance, allowing you to easily create pointers to values and retrieve their values when needed.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
}
todo := &ToDo{Text: mongorm.String("Buy milk")}

func StringVal

func StringVal(s *string) string

StringVal retrieves the value from a pointer to a string. If the pointer is nil, it returns an empty string. This function is useful for safely accessing the value of optional string fields in the schema without having to check for nil pointers every time.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
}
todo := &ToDo{Text: mongorm.String("Buy milk")}
textValue := mongorm.StringVal(todo.Text) // textValue will be "Buy milk"

func Text

func Text(field Field) bson.E

Text returns a text index key for the given field.

func Timestamp

func Timestamp(t time.Time) *time.Time

Timestamp creates a pointer to a time.Time value. This function is useful for creating pointers to time values when defining the schema struct for a MongORM instance, allowing you to easily manage timestamp fields in your documents.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
  TaskTime *time.Time `bson:"taskTime"`
}
todo := &ToDo{
    Text: mongorm.String("Buy milk"),
    TaskTime: mongorm.Timestamp(time.Now()),
}

func TimestampVal

func TimestampVal(t *time.Time) time.Time

TimestampVal retrieves the value from a pointer to a time.Time. If the pointer is nil, it returns the zero value of time.Time. This function is useful for safely accessing the value of optional time fields in the schema without having to check for nil pointers every time.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
  TaskTime *time.Time `bson:"taskTime"`
}
todo := &ToDo{
    Text: mongorm.String("Buy milk"),
    TaskTime: mongorm.Timestamp(time.Now()),
}
taskTimeValue := mongorm.TimestampVal(todo.TaskTime) // taskTimeValue will be the time value of TaskTime

func UniqueIndexModelFromKeys

func UniqueIndexModelFromKeys(keys ...bson.E) mongo.IndexModel

UniqueIndexModelFromKeys builds a unique index model from field-based keys.

func UnsetUpdateFromFields added in v1.0.3

func UnsetUpdateFromFields(fields ...Field) bson.M

UnsetUpdateFromFields builds an update document with $unset using schema fields.

Types

type AfterCreateHook

type AfterCreateHook[T any] interface {
	AfterCreate(*MongORM[T]) error
}

AfterCreateHook is called after executing a create operation. It allows you to perform any necessary cleanup or post-processing.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) AfterCreate(m *MongORM[ToDo]) error {
    // Perform cleanup or post-processing here
    return nil
}

type AfterDeleteHook

type AfterDeleteHook[T any] interface {
	AfterDelete(*MongORM[T]) error
}

AfterDeleteHook is called after executing a delete operation. It allows you to perform any necessary cleanup or post-processing.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) AfterDelete(m *MongORM[ToDo]) error {
    // Perform cleanup or post-processing here
    return nil
}

type AfterFinalizeHook

type AfterFinalizeHook[T any] interface {
	AfterFinalize(*MongORM[T]) error
}

AfterFinalizeHook is called after finalizing the MongORM instance. It allows you to perform any necessary cleanup or post-processing after the instance is finalized.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) AfterFinalize(m *MongORM[ToDo]) error {
    // Perform cleanup or post-processing here
    return nil
}

type AfterFindHook

type AfterFindHook[T any] interface {
	AfterFind(*MongORM[T]) error
}

AfterFindHook is called after executing a find operation. It allows you to perform any necessary cleanup or post-processing.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) AfterFind(m *MongORM[ToDo]) error {
    // Perform cleanup or post-processing here
    return nil
}

type AfterSaveHook

type AfterSaveHook[T any] interface {
	AfterSave(*MongORM[T]) error
}

AfterSaveHook is called after executing a save operation. It allows you to perform any necessary cleanup or post-processing.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) AfterSave(m *MongORM[ToDo]) error {
    // Perform cleanup or post-processing here
    return nil
}

type AfterUpdateHook

type AfterUpdateHook[T any] interface {
	AfterUpdate(*MongORM[T]) error
}

AfterUpdateHook is called after executing an update operation. It allows you to perform any necessary cleanup or post-processing.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) AfterUpdate(m *MongORM[ToDo]) error {
    // Perform cleanup or post-processing here
    return nil
}

type AggregateAlias

type AggregateAlias string

AggregateAlias is a helper type for naming output aliases in aggregate stages.

func Alias

func Alias(name string) AggregateAlias

Alias creates a reusable aggregate output alias.

func (AggregateAlias) Key

func (a AggregateAlias) Key() string

Key returns the raw alias string.

type BeforeCreateHook

type BeforeCreateHook[T any] interface {
	BeforeCreate(*MongORM[T]) error
}

BeforeCreateHook is called before executing a create operation. It allows you to modify the document or perform any necessary setup.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) BeforeCreate(m *MongORM[ToDo]) error {
    // Modify the document or perform setup here
    return nil
}

type BeforeDeleteHook

type BeforeDeleteHook[T any] interface {
	BeforeDelete(*MongORM[T], *bson.M) error
}

BeforeDeleteHook is called before executing a delete operation. It allows you to modify the query or perform any necessary setup.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) BeforeDelete(m *MongORM[ToDo], query *bson.M) error {
    // Modify the query or perform setup here
    return nil
}

type BeforeFinalizeHook

type BeforeFinalizeHook[T any] interface {
	BeforeFinalize(*MongORM[T]) error
}

BeforeFinalizeHook is called before finalizing the MongORM instance. It allows you to perform any necessary setup or modifications before the instance is finalized.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) BeforeFinalize(m *MongORM[ToDo]) error {
    // Perform setup or modifications here
    return nil
}

type BeforeFindHook

type BeforeFindHook[T any] interface {
	BeforeFind(*MongORM[T], *bson.M) error
}

BeforeFindHook is called before executing a find operation. It allows you to modify the query or perform any necessary setup.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) BeforeFind(m *MongORM[ToDo], query *bson.M) error {
    // Modify the query or perform setup here
    return nil
}

type BeforeSaveHook

type BeforeSaveHook[T any] interface {
	BeforeSave(*MongORM[T], *bson.M) error
}

BeforeSaveHook is called before executing a save operation. It allows you to modify the document or perform any necessary setup.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) BeforeSave(m *MongORM[ToDo], doc *bson.M) error {
    // Modify the document or perform setup here
    return nil
}

type BeforeUpdateHook

type BeforeUpdateHook[T any] interface {
	BeforeUpdate(*MongORM[T], *bson.M, *bson.M) error
}

BeforeUpdateHook is called before executing an update operation. It allows you to modify the query, update document, or perform any necessary setup.

Example usage:

type ToDo struct {
    Text *string `bson:"text"`
}

func (u *ToDo) BeforeUpdate(m *MongORM[ToDo], query *bson.M, update *bson.M) error {
    // Modify the query, update document, or perform setup here
    return nil
}

type BulkWriteBuilder

type BulkWriteBuilder[T any] struct {
	// contains filtered or unexported fields
}

BulkWriteBuilder builds typed MongoDB write models for bulk operations.

func NewBulkWriteBuilder

func NewBulkWriteBuilder[T any]() *BulkWriteBuilder[T]

NewBulkWriteBuilder creates a new bulk write model builder.

func (*BulkWriteBuilder[T]) DeleteMany

func (b *BulkWriteBuilder[T]) DeleteMany(filter bson.M) *BulkWriteBuilder[T]

DeleteMany appends a delete-many write model.

func (*BulkWriteBuilder[T]) DeleteManyBy added in v1.0.3

func (b *BulkWriteBuilder[T]) DeleteManyBy(field Field, value any) *BulkWriteBuilder[T]

DeleteManyBy appends a delete-many model using a schema field equality filter.

func (*BulkWriteBuilder[T]) DeleteOne

func (b *BulkWriteBuilder[T]) DeleteOne(filter bson.M) *BulkWriteBuilder[T]

DeleteOne appends a delete-one write model.

func (*BulkWriteBuilder[T]) DeleteOneBy added in v1.0.3

func (b *BulkWriteBuilder[T]) DeleteOneBy(field Field, value any) *BulkWriteBuilder[T]

DeleteOneBy appends a delete-one model using a schema field equality filter.

func (*BulkWriteBuilder[T]) InsertOne

func (b *BulkWriteBuilder[T]) InsertOne(document *T) *BulkWriteBuilder[T]

InsertOne appends an insert-one write model.

func (*BulkWriteBuilder[T]) Models

func (b *BulkWriteBuilder[T]) Models() []mongo.WriteModel

Models returns the accumulated write models.

func (*BulkWriteBuilder[T]) ReplaceOne

func (b *BulkWriteBuilder[T]) ReplaceOne(
	filter bson.M,
	replacement *T,
	upsert bool,
) *BulkWriteBuilder[T]

ReplaceOne appends a replace-one write model.

func (*BulkWriteBuilder[T]) ReplaceOneBy added in v1.0.3

func (b *BulkWriteBuilder[T]) ReplaceOneBy(
	field Field,
	value any,
	replacement *T,
	upsert bool,
) *BulkWriteBuilder[T]

ReplaceOneBy appends a replace-one model using a schema field equality filter.

func (*BulkWriteBuilder[T]) UpdateMany

func (b *BulkWriteBuilder[T]) UpdateMany(
	filter bson.M,
	update bson.M,
	upsert bool,
) *BulkWriteBuilder[T]

UpdateMany appends an update-many write model.

func (*BulkWriteBuilder[T]) UpdateManyBy added in v1.0.3

func (b *BulkWriteBuilder[T]) UpdateManyBy(
	field Field,
	value any,
	update bson.M,
	upsert bool,
) *BulkWriteBuilder[T]

UpdateManyBy appends an update-many model using a schema field equality filter.

func (*BulkWriteBuilder[T]) UpdateOne

func (b *BulkWriteBuilder[T]) UpdateOne(
	filter bson.M,
	update bson.M,
	upsert bool,
) *BulkWriteBuilder[T]

UpdateOne appends an update-one write model.

func (*BulkWriteBuilder[T]) UpdateOneBy added in v1.0.3

func (b *BulkWriteBuilder[T]) UpdateOneBy(
	field Field,
	value any,
	update bson.M,
	upsert bool,
) *BulkWriteBuilder[T]

UpdateOneBy appends an update-one model using a schema field equality filter.

type Field

type Field interface {
	BSONName() string
}

Field represents a field in the schema of a MongORM instance. It provides methods to retrieve the BSON name of the field, which is used for constructing queries and updates. The Field interface is implemented by specific field types (e.g., StringField, Int64Field) that correspond to the Go types used in the schema struct.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
}
var ToDoFields = mongorm.FieldsOf[ToDo, struct {
  Text *primitives.StringField
}]()

func FieldPath added in v1.0.3

func FieldPath(base Field, suffix string) Field

FieldPath appends a dotted suffix path to an existing field path.

func Indexed added in v1.0.3

func Indexed(field Field, index int) Field

Indexed builds a field path for a specific array index. Example: Indexed(ToDoFields.Items, 2) => "items.2"

func NewFieldFromSchemaType added in v1.0.3

func NewFieldFromSchemaType(t reflect.Type, name string) (Field, bool)

Creates a Field object based on a schema field type. This lets schema definitions explicitly select a primitive wrapper, even when the model field Go type differs.

func NewFieldFromType

func NewFieldFromType(t reflect.Type, name string) Field

Creates a Field object based on the Go type. This is used to build the schema information for the MongORM instance.

> NOTE: This function is internal only.

func Positional added in v1.0.3

func Positional(field Field) Field

Positional builds a field path using MongoDB positional operator `$`. Example: Positional(ToDoFields.Items) => "items.$"

func PositionalAll added in v1.0.3

func PositionalAll(field Field) Field

PositionalAll builds a field path using MongoDB all positional operator `$[]`. Example: PositionalAll(ToDoFields.Items) => "items.$[]"

func PositionalFiltered added in v1.0.3

func PositionalFiltered(field Field, identifier string) Field

PositionalFiltered builds a field path using MongoDB filtered positional operator `$[identifier]`. Example: PositionalFiltered(ToDoFields.Items, "item") => "items.$[item]"

func RawField added in v1.0.3

func RawField(path string) Field

RawField builds a Field from a raw BSON path.

type FieldValuePair added in v1.0.3

type FieldValuePair struct {
	Field Field
	Value any
}

FieldValuePair is a field/value helper for field-only update builders.

type GeoLineString

type GeoLineString struct {
	Type        string      `bson:"type" json:"type"`
	Coordinates [][]float64 `bson:"coordinates" json:"coordinates"`
}

GeoLineString represents a GeoJSON LineString.

func NewGeoLineString

func NewGeoLineString(coordinates ...[]float64) *GeoLineString

type GeoPoint

type GeoPoint struct {
	Type        string    `bson:"type" json:"type"`
	Coordinates []float64 `bson:"coordinates" json:"coordinates"`
}

GeoPoint represents a GeoJSON Point.

func NewGeoPoint

func NewGeoPoint(longitude float64, latitude float64) *GeoPoint

type GeoPolygon

type GeoPolygon struct {
	Type        string        `bson:"type" json:"type"`
	Coordinates [][][]float64 `bson:"coordinates" json:"coordinates"`
}

GeoPolygon represents a GeoJSON Polygon.

func NewGeoPolygon

func NewGeoPolygon(rings ...[][]float64) *GeoPolygon

type ModelTags

type ModelTags string
const (
	ModelTagDatabase         ModelTags = "connection:database"
	ModelTagCollection       ModelTags = "connection:collection"
	ModelTagConnectionString ModelTags = "connection:url"
)

Connection tags These tags are used to specify connection information for the MongORM instance, such as the database name, collection name, and connection string. These tags can be included in the struct fields of the schema to provide the necessary information for connecting to the MongoDB database. The MongORM instance will use these tags to configure its connection settings when performing operations. Example usage:

type ToDo struct {
   Text *string `bson:"text"`
   // MongORM options
   connectionString *string `mongorm:"[connection_string],connection:url"`
}
const (
	ModelTagPrimary            ModelTags = "primary"
	ModelTagVersion            ModelTags = "version"
	ModelTagReadonly           ModelTags = "readonly"
	ModelTagTimestampCreatedAt ModelTags = "timestamp:created_at"
	ModelTagTimestampUpdatedAt ModelTags = "timestamp:updated_at"
)

Field tags These tags are used to specify field-level options for the MongORM instance, such as primary key fields, read-only fields, and timestamp fields. These tags can be included in the struct fields of the schema to provide additional information about how the fields should be treated during operations. The MongORM instance will use these tags to determine how to handle the fields when performing operations such as updates and saves. Example usage:

type ToDo struct {
   Text *string `bson:"text"`
   // MongORM Tags
   ID *string `bson:"_id" mongorm:"primary"`
   CreatedAt *time.Time `bson:"created_at" mongorm:"timestamp:created_at"`
   UpdatedAt *time.Time `bson:"updated_at" mongorm:"timestamp:updated_at"`
}

type MongORM

type MongORM[T any] struct {
	// contains filtered or unexported fields
}

MongORMOperations holds the accumulated operations for a MongORM instance, including query filters, update documents, and other operation-specific information. This struct is used internally by the MongORM instance to manage the state of ongoing operations.

> NOTE: This struct is not intended for public use.

func FromOptions

func FromOptions[T any](schema *T, options *MongORMOptions) *MongORM[T]

FromOptions creates a new MongORM instance with the provided schema and options. This function allows you to customize the MongORM instance with specific settings for timestamps, collection and database names, and the MongoDB client. If options is nil, default settings will be used.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
}
options := &mongorm.MongORMOptions{
    Timestamps: true,
    CollectionName: ptr("todos"),
    DatabaseName: ptr("mydb"),
    MongoClient: myMongoClient,
}
orm := mongorm.FromOptions(&ToDo{}, options)

func New

func New[T any](schema *T) *MongORM[T]

Creates a new MongORM instance with the provided schema and options.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
	// MongORM options
	connectionString *string `mongorm:"[connection_string],connection:url"`
	database         *string `mongorm:"[database],connection:database"`
	collection       *string `mongorm:"[collection],connection:collection"`
}
orm := mongorm.New(&ToDo{})

func (*MongORM[T]) AddFieldStage

func (m *MongORM[T]) AddFieldStage(alias AggregateAlias, value any) *MongORM[T]

AddFieldStage appends a single field in $addFields using a reusable alias helper.

func (*MongORM[T]) AddFieldsStage

func (m *MongORM[T]) AddFieldsStage(fields bson.M) *MongORM[T]

AddFieldsStage appends a $addFields stage.

func (*MongORM[T]) AddToSetData added in v1.0.8

func (m *MongORM[T]) AddToSetData(field any, value any) *MongORM[T]

AddToSetData adds or overrides a single field/value in the current $addToSet update document. It accepts a schema Field, so nested fields are supported via field paths.

func (*MongORM[T]) AddToSetEachData added in v1.0.8

func (m *MongORM[T]) AddToSetEachData(field any, values []any) *MongORM[T]

AddToSetEachData appends multiple values uniquely using MongoDB's $addToSet + $each syntax.

func (*MongORM[T]) After

func (m *MongORM[T]) After(field Field, cursor any) *MongORM[T]

After adds a keyset-style pagination filter: field > cursor.

func (*MongORM[T]) Aggregate

func (m *MongORM[T]) Aggregate(
	ctx context.Context,
	pipeline bson.A,
	opts ...options.Lister[options.AggregateOptions],
) (*MongORMCursor[T], error)

Aggregate runs an aggregation pipeline and returns a MongORM cursor decoding each result document into T.

func (*MongORM[T]) AggregatePipeline

func (m *MongORM[T]) AggregatePipeline(
	ctx context.Context,
	opts ...options.Lister[options.AggregateOptions],
) (*MongORMCursor[T], error)

AggregatePipeline runs the accumulated fluent pipeline stages.

func (*MongORM[T]) AggregatePipelineRaw

func (m *MongORM[T]) AggregatePipelineRaw(
	ctx context.Context,
	opts ...options.Lister[options.AggregateOptions],
) (*mongo.Cursor, error)

AggregatePipelineRaw runs the accumulated fluent pipeline stages and returns the underlying MongoDB cursor.

func (*MongORM[T]) AggregateRaw

func (m *MongORM[T]) AggregateRaw(
	ctx context.Context,
	pipeline bson.A,
	opts ...options.Lister[options.AggregateOptions],
) (*mongo.Cursor, error)

AggregateRaw runs an aggregation pipeline and returns a raw MongoDB cursor.

func (*MongORM[T]) Before

func (m *MongORM[T]) Before(field Field, cursor any) *MongORM[T]

Before adds a keyset-style pagination filter: field < cursor.

func (*MongORM[T]) BulkWrite

func (m *MongORM[T]) BulkWrite(
	ctx context.Context,
	models []mongo.WriteModel,
	opts ...options.Lister[options.BulkWriteOptions],
) (*mongo.BulkWriteResult, error)

BulkWrite executes multiple write models in a single request.

func (*MongORM[T]) BulkWriteInTransaction

func (m *MongORM[T]) BulkWriteInTransaction(
	ctx context.Context,
	models []mongo.WriteModel,
	bulkOpts ...options.Lister[options.BulkWriteOptions],
) (*mongo.BulkWriteResult, error)

BulkWriteInTransaction executes a bulk write operation inside a transaction.

func (*MongORM[T]) Count

func (m *MongORM[T]) Count(
	ctx context.Context,
	opts ...options.Lister[options.CountOptions],
) (int64, error)

Count returns the number of documents that match the current filters.

func (*MongORM[T]) DecData added in v1.0.7

func (m *MongORM[T]) DecData(field any, value int64) *MongORM[T]

DecData decrements a field using MongoDB's $inc with a negative delta.

Example usage:

orm.Where(ToDoFields.ID.Eq(id)).DecData(ToDoFields.Count, 1).Save(ctx)
// equivalent raw update: {"$inc": {"count": -1}}

func (*MongORM[T]) DecFloat64Data added in v1.0.24

func (m *MongORM[T]) DecFloat64Data(field any, value float64) *MongORM[T]

DecFloat64Data decrements a numeric field using MongoDB's $inc with a negative float64 delta.

Example usage:

orm.Where(ToDoFields.ID.Eq(id)).DecFloat64Data(ToDoFields.Score, 0.5).Save(ctx)

func (*MongORM[T]) Delete

func (m *MongORM[T]) Delete(
	ctx context.Context,
) error

Delete removes a single document that matches the specified query criteria from the collection. It uses the DeleteOne method of the MongoDB collection to execute the delete operation. The query is constructed based on the state of the MongORM instance, and it typically includes a primary key or other unique identifier to ensure that only one document is deleted. It returns an error if the operation fails or if no document matches the query criteria.

Example usage:

err := mongormInstance.Delete(ctx)
if err != nil {
    // Handle error
} else {
    // Document deleted successfully
}

func (*MongORM[T]) DeleteMulti

func (m *MongORM[T]) DeleteMulti(
	ctx context.Context,
	opts ...options.Lister[options.DeleteManyOptions],
) (*mongo.DeleteResult, error)

DeleteMulti removes all documents that match the current filters. It returns a DeleteResult containing the number of removed documents.

func (*MongORM[T]) Distinct

func (m *MongORM[T]) Distinct(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]any, error)

Distinct returns all unique values of the given field among documents that match the current filters.

func (*MongORM[T]) DistinctBool

func (m *MongORM[T]) DistinctBool(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]bool, error)

DistinctBool returns distinct boolean values for the given field.

func (*MongORM[T]) DistinctFloat64

func (m *MongORM[T]) DistinctFloat64(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]float64, error)

DistinctFloat64 returns distinct numeric values (as float64) for the given field.

func (*MongORM[T]) DistinctInt64

func (m *MongORM[T]) DistinctInt64(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]int64, error)

DistinctInt64 returns distinct integer values (as int64) for the given field.

func (*MongORM[T]) DistinctObjectIDs

func (m *MongORM[T]) DistinctObjectIDs(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]bson.ObjectID, error)

DistinctObjectIDs returns distinct ObjectID values for the given field.

func (*MongORM[T]) DistinctStrings

func (m *MongORM[T]) DistinctStrings(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]string, error)

DistinctStrings returns distinct string values for the given field.

func (*MongORM[T]) DistinctTimes

func (m *MongORM[T]) DistinctTimes(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.DistinctOptions],
) ([]time.Time, error)

DistinctTimes returns distinct time values for the given field.

func (*MongORM[T]) Document

func (m *MongORM[T]) Document() *T

Document returns the current document schema of the MongORM instance. This is useful for accessing the underlying document structure for queries and updates. The returned value is a pointer to the schema struct, allowing the caller to modify the document fields directly.

Example usage:

doc := mongormInstance.Document()
doc.Text = ptr("New ToDo Item")

func (*MongORM[T]) Ensure2DSphereIndex

func (m *MongORM[T]) Ensure2DSphereIndex(
	ctx context.Context,
	field Field,
	opts ...options.Lister[options.CreateIndexesOptions],
) (string, error)

Ensure2DSphereIndex creates a 2dsphere index for the provided field.

func (*MongORM[T]) EnsureGeoDefaults

func (m *MongORM[T]) EnsureGeoDefaults(
	ctx context.Context,
	geoField Field,
	supportingKeys []bson.E,
	opts ...options.Lister[options.CreateIndexesOptions],
) ([]string, error)

EnsureGeoDefaults creates the baseline geospatial indexes for a field: - required 2dsphere index on geoField - optional supporting index (if supportingKeys are provided)

func (*MongORM[T]) EnsureIndex

func (m *MongORM[T]) EnsureIndex(
	ctx context.Context,
	model mongo.IndexModel,
	opts ...options.Lister[options.CreateIndexesOptions],
) (string, error)

EnsureIndex creates an index using the provided model.

func (*MongORM[T]) EnsureIndexes

func (m *MongORM[T]) EnsureIndexes(
	ctx context.Context,
	models []mongo.IndexModel,
	opts ...options.Lister[options.CreateIndexesOptions],
) ([]string, error)

EnsureIndexes creates multiple indexes in one call.

func (*MongORM[T]) FacetStage

func (m *MongORM[T]) FacetStage(facets bson.M) *MongORM[T]

FacetStage appends a $facet stage.

func (*MongORM[T]) FacetStageEntries

func (m *MongORM[T]) FacetStageEntries(entries ...bson.E) *MongORM[T]

FacetStageEntries appends a $facet stage from facet entries built with Facet().

func (*MongORM[T]) Find

func (m *MongORM[T]) Find(
	ctx context.Context,
	opts ...options.Lister[options.FindOneOptions],
) error

Find retrieves a single document that matches the specified query criteria and decodes it into the schema of the MongORM instance. It uses the FindOne method of the MongoDB collection to execute the query and obtain the matching document. The query is constructed based on the state of the MongORM instance, and additional options can be provided using the opts parameter. It returns an error if the operation fails or if no document matches the query criteria.

Example usage:

err := mongormInstance.Find(ctx)
if err != nil {
    if errors.Is(err, mongo.ErrNoDocuments) {
        // No document found
    } else {
        // Handle error
    }
} else {
    // Document found and decoded into mongormInstance.schema
}

func (*MongORM[T]) FindAll

func (m *MongORM[T]) FindAll(
	ctx context.Context,
	opts ...options.Lister[options.FindOptions],
) (*MongORMCursor[T], error)

FindAll retrieves all documents that match the specified query criteria and returns a cursor for iterating over the results. It uses the Find method of the MongoDB collection to execute the query and obtain a cursor for the matching documents. The query is constructed based on the state of the MongORM instance, and additional options can be provided using the opts parameter. The caller is responsible for closing the cursor when done to free up resources. It is recommended to use the cursor's Next method for large result sets to avoid loading all documents into memory at once.

Example usage:

cursor, err := mongormInstance.FindAll(ctx)
if err != nil {
    // Handle error
} else {
    // Use cursor
}

func (*MongORM[T]) FindOneAndUpdate added in v1.0.11

func (m *MongORM[T]) FindOneAndUpdate(
	ctx context.Context,
	opts ...options.Lister[options.FindOneAndUpdateOptions],
) error

FindOneAndUpdate updates a single existing document that matches the current query criteria and decodes the updated document back into the schema.

Unlike Save/Update, this method never performs an upsert. If no document matches the query criteria, it returns ErrNotFound.

Example usage:

err := mongormInstance.Where(...).Set(...).FindOneAndUpdate(ctx)
if err != nil {
    // Handle error
}

func (*MongORM[T]) First

func (m *MongORM[T]) First(
	ctx context.Context,
	opts ...options.Lister[options.FindOneOptions],
) error

First retrieves the first document that matches the specified query criteria and decodes it into the schema of the MongORM instance. It uses the FindOne method of the MongoDB collection to execute the query and obtain the matching document. The query is constructed based on the state of the MongORM instance, and additional options can be provided using the opts parameter. It returns an error if the operation fails or if no document matches the query criteria.

Example usage:

err := mongormInstance.First(ctx)
if err != nil {
    if errors.Is(err, mongo.ErrNoDocuments) {
        // No document found
    } else {
        // Handle error
    }
} else {
    // Document found and decoded into mongormInstance.schema
}

func (*MongORM[T]) GetRawQuery added in v1.0.17

func (m *MongORM[T]) GetRawQuery() bson.M

GetRawQuery returns a debug copy of the currently accumulated query document. This is useful for logging and troubleshooting query builder state before execution.

func (*MongORM[T]) GetRawUpdate added in v1.0.17

func (m *MongORM[T]) GetRawUpdate() bson.M

GetRawUpdate returns a debug copy of the currently accumulated update document. This is useful for logging and troubleshooting update builder state before execution.

func (*MongORM[T]) GetResolvedRawQuery added in v1.0.18

func (m *MongORM[T]) GetResolvedRawQuery() (bson.M, error)

GetResolvedRawQuery returns a debug copy of the effective query document used by single-document find/update/delete operations. It includes accumulated query builder filters and schema-derived selectors (such as primary key or non-zero/non-nil fields on the current schema).

func (*MongORM[T]) GroupCountBy

func (m *MongORM[T]) GroupCountBy(field Field, as string) *MongORM[T]

GroupCountBy appends a $group stage that counts documents by the given field.

func (*MongORM[T]) GroupCountByAlias

func (m *MongORM[T]) GroupCountByAlias(field Field, as AggregateAlias) *MongORM[T]

GroupCountByAlias appends a $group count stage using a reusable alias helper.

func (*MongORM[T]) GroupStage

func (m *MongORM[T]) GroupStage(group bson.M) *MongORM[T]

GroupStage appends a $group stage.

func (*MongORM[T]) GroupSumBy

func (m *MongORM[T]) GroupSumBy(groupBy Field, sumField Field, as string) *MongORM[T]

GroupSumBy appends a $group stage that sums the given value field, grouped by field.

func (*MongORM[T]) GroupSumByAlias

func (m *MongORM[T]) GroupSumByAlias(groupBy Field, sumField Field, as AggregateAlias) *MongORM[T]

GroupSumByAlias appends a $group sum stage using a reusable alias helper.

func (*MongORM[T]) IncData added in v1.0.7

func (m *MongORM[T]) IncData(field any, value any) *MongORM[T]

IncData adds or overrides a single field/value in the current $inc update document. It accepts a schema Field, so nested fields are supported via field paths.

Example usage:

orm.Where(ToDoFields.ID.Eq(id)).IncData(ToDoFields.Count, int64(2)).Save(ctx)
orm.Where(ToDoFields.ID.Eq(id)).IncData(ToDoFields.User.Score, 1).Save(ctx)

func (*MongORM[T]) IncFloat64Data added in v1.0.24

func (m *MongORM[T]) IncFloat64Data(field any, value float64) *MongORM[T]

IncFloat64Data increments a numeric field using MongoDB's $inc with a float64 delta.

Example usage:

orm.Where(ToDoFields.ID.Eq(id)).IncFloat64Data(ToDoFields.Score, 1.25).Save(ctx)

func (*MongORM[T]) IsModified added in v1.0.3

func (m *MongORM[T]) IsModified(field any) bool

func (*MongORM[T]) JSON

func (m *MongORM[T]) JSON(doc *T) (map[string]any, error)

JSON converts the provided document struct into a map[string]any representation. This is useful for constructing query filters and update documents in a flexible format that can be easily manipulated. The method uses JSON marshaling and unmarshaling to perform the conversion, which allows it to handle nested structs and complex field types.

Example usage:

doc := &ToDo{Text: ptr("New ToDo Item")}
docMap, err := mongormInstance.JSON(doc)
if err != nil {
    // Handle error
} else {
    // Use docMap for queries or updates
}

func (*MongORM[T]) Limit

func (m *MongORM[T]) Limit(value int64) *MongORM[T]

Limit sets the maximum number of documents returned by find operations. For First()/Find(), this value is ignored because the operation always returns one document.

func (*MongORM[T]) LimitStage

func (m *MongORM[T]) LimitStage(limit int64) *MongORM[T]

LimitStage appends a $limit stage.

func (*MongORM[T]) LookupByStage added in v1.0.3

func (m *MongORM[T]) LookupByStage(
	from string,
	localField Field,
	foreignField Field,
	as AggregateAlias,
) *MongORM[T]

LookupByStage appends a $lookup stage using schema fields for local/foreign keys.

func (*MongORM[T]) LookupPipelineStage

func (m *MongORM[T]) LookupPipelineStage(
	from string,
	let bson.M,
	pipeline bson.A,
	as string,
) *MongORM[T]

LookupPipelineStage appends a pipeline-based $lookup stage.

func (*MongORM[T]) LookupStage

func (m *MongORM[T]) LookupStage(
	from string,
	localField string,
	foreignField string,
	as string,
) *MongORM[T]

LookupStage appends a basic $lookup stage.

func (*MongORM[T]) MatchBy

func (m *MongORM[T]) MatchBy(field Field, value any) *MongORM[T]

MatchBy appends a $match stage for a field/value pair.

func (*MongORM[T]) MatchExpr

func (m *MongORM[T]) MatchExpr(expr bson.M) *MongORM[T]

MatchExpr appends a $match stage from an expression built by field operators such as Eq/Gt/Reg.

func (*MongORM[T]) MatchStage

func (m *MongORM[T]) MatchStage(match bson.M) *MongORM[T]

MatchStage appends a $match stage.

func (*MongORM[T]) MatchWhere

func (m *MongORM[T]) MatchWhere() *MongORM[T]

MatchWhere appends a $match stage from accumulated Where()/WhereBy() filters.

func (*MongORM[T]) ModifiedFields added in v1.0.3

func (m *MongORM[T]) ModifiedFields() []Field

func (*MongORM[T]) ModifiedValue added in v1.0.13

func (m *MongORM[T]) ModifiedValue(field any) (oldValue any, newValue any, ok bool)

func (*MongORM[T]) OrWhere added in v1.0.6

func (m *MongORM[T]) OrWhere(expr bson.M) *MongORM[T]

OrWhere adds a query filter to the MongORM instance under the $or operator. Multiple OrWhere calls are grouped together in a single $or array.

Example usage:

orm.OrWhere(fieldType.Text.Eq("A")).OrWhere(fieldType.Text.Eq("B"))

func (*MongORM[T]) OrWhereAnd added in v1.0.6

func (m *MongORM[T]) OrWhereAnd(exprs ...bson.M) *MongORM[T]

OrWhereAnd adds a grouped AND expression as one branch of the $or operator. This is useful for building queries like: (...existing filters...) AND ((A AND B) OR (C AND D)).

Example usage:

orm.
	OrWhereAnd(fieldType.Status.Eq("pending"), fieldType.RunAt.Lte(now)).
	OrWhereAnd(fieldType.LockedUntil.NotExists(), fieldType.LockedUntil.Lte(now))

func (*MongORM[T]) OrWhereBy added in v1.0.6

func (m *MongORM[T]) OrWhereBy(field Field, value any) *MongORM[T]

OrWhereBy adds a field/value query filter to the MongORM instance under the $or operator.

Example usage:

orm.OrWhereBy(fieldType.Text, "A").OrWhereBy(fieldType.Text, "B")

func (*MongORM[T]) PaginateAfter

func (m *MongORM[T]) PaginateAfter(field Field, cursor any, size int64) *MongORM[T]

PaginateAfter applies keyset pagination in ascending order for the given field.

func (*MongORM[T]) PaginateBefore

func (m *MongORM[T]) PaginateBefore(field Field, cursor any, size int64) *MongORM[T]

PaginateBefore applies keyset pagination in descending order for the given field.

func (*MongORM[T]) Pipeline

func (m *MongORM[T]) Pipeline(stages ...bson.M) *MongORM[T]

Pipeline appends one or more aggregation stages to the current aggregate pipeline.

func (*MongORM[T]) PopData added in v1.0.8

func (m *MongORM[T]) PopData(field any, value int) *MongORM[T]

PopData adds or overrides a single field/value in the current $pop update document. value must be either -1 (remove first) or 1 (remove last).

func (*MongORM[T]) PopFirstData added in v1.0.8

func (m *MongORM[T]) PopFirstData(field any) *MongORM[T]

PopFirstData removes the first element from an array field.

func (*MongORM[T]) PopLastData added in v1.0.8

func (m *MongORM[T]) PopLastData(field any) *MongORM[T]

PopLastData removes the last element from an array field.

func (*MongORM[T]) ProjectIncludeFields

func (m *MongORM[T]) ProjectIncludeFields(fields ...Field) *MongORM[T]

ProjectIncludeFields appends a $project stage that includes only the provided fields.

func (*MongORM[T]) ProjectStage

func (m *MongORM[T]) ProjectStage(project bson.M) *MongORM[T]

ProjectStage appends a $project stage.

func (*MongORM[T]) Projection

func (m *MongORM[T]) Projection(value any) *MongORM[T]

Projection sets the fields returned by find operations. Example: bson.M{"text": 1, "count": 1}

func (*MongORM[T]) ProjectionExclude added in v1.0.3

func (m *MongORM[T]) ProjectionExclude(fields ...Field) *MongORM[T]

ProjectionExclude sets projection to exclude the given schema fields.

func (*MongORM[T]) ProjectionInclude added in v1.0.3

func (m *MongORM[T]) ProjectionInclude(fields ...Field) *MongORM[T]

ProjectionInclude sets projection to include only the given schema fields.

func (*MongORM[T]) PullData added in v1.0.8

func (m *MongORM[T]) PullData(field any, value any) *MongORM[T]

PullData adds or overrides a single field/value in the current $pull update document. It accepts a schema Field, so nested fields are supported via field paths.

func (*MongORM[T]) PushData added in v1.0.8

func (m *MongORM[T]) PushData(field any, value any) *MongORM[T]

PushData adds or overrides a single field/value in the current $push update document. It accepts a schema Field, so nested fields are supported via field paths.

func (*MongORM[T]) PushEachData added in v1.0.8

func (m *MongORM[T]) PushEachData(field any, values []any) *MongORM[T]

PushEachData appends multiple values using MongoDB's $push + $each syntax.

func (*MongORM[T]) ResetPipeline

func (m *MongORM[T]) ResetPipeline() *MongORM[T]

ResetPipeline clears accumulated aggregation stages.

func (*MongORM[T]) Save

Save performs an upsert operation on a single document based on the state of the MongORM instance. It checks if the document already exists by looking for a primary key or other unique identifier in the query filters. If the document exists, it updates the existing document with the new values from the MongORM instance. If the document does not exist, it inserts a new document into the collection. The method also applies any necessary timestamps and executes any defined hooks before and after the save operation. It returns an error if the operation fails.

Example usage:

err := mongormInstance.Save(ctx)
if err != nil {
    // Handle error
} else {
    // Document saved successfully
}

func (*MongORM[T]) SaveMulti

func (m *MongORM[T]) SaveMulti(
	ctx context.Context,
	opts ...options.Lister[options.UpdateManyOptions],
) (*mongo.UpdateResult, error)

SaveMulti performs an update operation on multiple documents that match the specified query criteria. It uses the UpdateMany method of the MongoDB collection to apply the update operations to all matching documents. The query and update operations are constructed based on the state of the MongORM instance. The caller can provide additional options for the UpdateMany operation using the opts parameter. It returns an UpdateResult containing information about the operation, such as the number of documents matched and modified, or an error if the operation fails.

Example usage:

updateResult, err := mongormInstance.SaveMulti(ctx)
if err != nil {
    // Handle error
} else {
    // Use updateResult
}

func (*MongORM[T]) Set

func (m *MongORM[T]) Set(value *T) *MongORM[T]

Set adds the specified fields and values to the update document for the current operation. It takes a pointer to a struct of type T, which represents the fields to be updated. The method iterates through the fields of the struct, checking for non-zero values and adding them to the $set operator in the update document. It also handles timestamp fields if the Timestamps option is enabled. The method returns the MongORM instance, allowing for method chaining.

Example usage:

type ToDo struct {
   Text *string `bson:"text"`
   // MongORM options
}

toDo := &ToDo{Text: mongorm.String("Buy milk")}
orm := mongorm.New(&ToDo{})
orm.Set(&ToDo{Text: mongorm.String("Canceled Buy milk")})
err := orm.Save(ctx)

func (*MongORM[T]) SetData added in v1.0.3

func (m *MongORM[T]) SetData(field any, value any) *MongORM[T]

SetData adds or overrides a single field/value in the current $set update document. It accepts a schema Field, so nested fields are supported via field paths (for example: `ToDoFields.User.Email` => `user.email`).

func (*MongORM[T]) SetOnInsert added in v1.0.23

func (m *MongORM[T]) SetOnInsert(value *T) *MongORM[T]

SetOnInsert adds fields and values to the $setOnInsert update document. Values are only applied by MongoDB when an upsert operation inserts a new document.

func (*MongORM[T]) SetOnInsertData added in v1.0.23

func (m *MongORM[T]) SetOnInsertData(field any, value any) *MongORM[T]

SetOnInsertData adds or overrides a single field/value in the current $setOnInsert update document. It accepts a schema Field, so nested fields are supported via field paths.

func (*MongORM[T]) Skip

func (m *MongORM[T]) Skip(value int64) *MongORM[T]

Skip sets the number of documents to skip before returning results for find operations.

func (*MongORM[T]) SkipStage

func (m *MongORM[T]) SkipStage(skip int64) *MongORM[T]

SkipStage appends a $skip stage.

func (*MongORM[T]) Sort

func (m *MongORM[T]) Sort(value any) *MongORM[T]

Sort sets the sort order for find operations. It accepts the same values supported by MongoDB options, such as bson.D{{"field", 1}} or bson.M{"field": -1}.

func (*MongORM[T]) SortAsc added in v1.0.3

func (m *MongORM[T]) SortAsc(field Field) *MongORM[T]

SortAsc sets ascending sort using a schema field.

func (*MongORM[T]) SortBy added in v1.0.3

func (m *MongORM[T]) SortBy(field Field, direction int) *MongORM[T]

SortBy sets sort using a schema field and direction. Use 1 for ascending and -1 for descending.

func (*MongORM[T]) SortByStage

func (m *MongORM[T]) SortByStage(field Field, direction int) *MongORM[T]

SortByStage appends a $sort stage using a schema field and direction. Use 1 for ascending and -1 for descending.

func (*MongORM[T]) SortDesc added in v1.0.3

func (m *MongORM[T]) SortDesc(field Field) *MongORM[T]

SortDesc sets descending sort using a schema field.

func (*MongORM[T]) SortStage

func (m *MongORM[T]) SortStage(sort any) *MongORM[T]

SortStage appends a $sort stage.

func (*MongORM[T]) Unset

func (m *MongORM[T]) Unset(value *T) *MongORM[T]

Save performs an upsert operation, updating an existing document if it exists or inserting a new one if it does not. The method applies any necessary timestamps and executes any defined hooks before and after the save operation. It returns an error if the operation fails.

Example usage:

type ToDo struct {
   Text *string `bson:"text"`
   // MongORM options
}

toDo := &ToDo{Text: mongorm.String("Buy milk")}
orm := mongorm.New(&ToDo{})
orm.Unset(&ToDo{Text: nil})
err := orm.Save(ctx)

func (*MongORM[T]) UnsetData added in v1.0.3

func (m *MongORM[T]) UnsetData(field any) *MongORM[T]

UnsetData adds or overrides a single field in the current $unset update document. It accepts a schema Field, so nested fields are supported via field paths (for example: `ToDoFields.User.Email` => `user.email`).

func (*MongORM[T]) UnwindByStage added in v1.0.3

func (m *MongORM[T]) UnwindByStage(field Field) *MongORM[T]

UnwindByStage appends a $unwind stage using a schema field path.

func (*MongORM[T]) UnwindStage

func (m *MongORM[T]) UnwindStage(path string) *MongORM[T]

UnwindStage appends a $unwind stage.

func (*MongORM[T]) Where

func (m *MongORM[T]) Where(expr bson.M) *MongORM[T]

Where adds a query filter to the MongORM instance as plain top-level query fields. Repeated calls merge into the same query document.

Example usage:

orm.Where(bson.M{"age": bson.M{"$gt": 30}}).Where(bson.M{"name": "John"})
// OR
orm.Where(fielType.Age.Gt(30)).Where(fieldType.Name.Eq("John"))

func (*MongORM[T]) WhereAnd added in v1.0.20

func (m *MongORM[T]) WhereAnd(exprs ...bson.M) *MongORM[T]

WhereAnd adds one or more query expressions under the $and operator. Use this when explicit $and grouping is required.

func (*MongORM[T]) WhereBy

func (m *MongORM[T]) WhereBy(field Field, value any) *MongORM[T]

WhereBy adds a query filter for a specific field and value to the MongORM instance. It constructs a bson.M expression for the given field and value and merges it as top-level query fields.

Example usage:

orm.WhereBy(fieldType.Age, 30).WhereBy(fieldType.Name, "John")

func (*MongORM[T]) WithTransaction

func (m *MongORM[T]) WithTransaction(
	ctx context.Context,
	fn func(txCtx context.Context) error,
	opts ...options.Lister[options.TransactionOptions],
) error

WithTransaction executes fn within a MongoDB transaction.

The callback receives a transaction-bound context. Any MongORM operation using that context will run in the same transaction session.

type MongORMCursor

type MongORMCursor[T any] struct {
	MongoCursor *mongo.Cursor `json:"-"`
	// contains filtered or unexported fields
}

MongORMCursor provides an abstraction over the MongoDB cursor, allowing for easy iteration and retrieval of documents as MongORM instances. It encapsulates the MongoDB cursor and a reference to the MongORM instance to facilitate decoding documents into the appropriate schema. The cursor should be closed when done to free up resources.

Example usage:

cursor, err := mongormInstance.FindAll(ctx)
if err != nil {
    // Handle error
} else {
    mongormCursor := &MongORMCursor[ToDo]{
        MongoCursor: cursor,
        m:           mongormInstance,
    }
    // Use mongormCursor to iterate over results
}

func (*MongORMCursor[T]) All

func (c *MongORMCursor[T]) All(ctx context.Context) ([]*MongORM[T], error)

All retrieves all remaining documents from the cursor and decodes them into a slice of MongORM instances. The caller is responsible for closing the cursor when done. The context can be used to cancel the operation if needed. It is recommended to use the cursor's Next method for large result sets to avoid loading all documents into memory at once.

Example usage:

cursors, err := mongormCursor.All(ctx)
if err != nil {
    // Handle error
} else {
    // Use the cursors
}

func (*MongORMCursor[T]) Close

func (c *MongORMCursor[T]) Close(ctx context.Context) error

Close closes the cursor and releases any resources associated with it. The context can be used to cancel the operation if needed. It is important to close the cursor when done to avoid resource leaks.

Example usage:

err := mongormCursor.Close(ctx)
if err != nil {
    // Handle error
}

func (*MongORMCursor[T]) Current added in v1.0.5

func (c *MongORMCursor[T]) Current() *MongORM[T]

Current returns the current document as a MongORM instance. It should be called after a successful call to Next. If there is no current document (e.g., before the first call to Next or after reaching the end of the cursor), it returns nil.

Example usage:

if mongormCursor.Next(ctx) {
    current := mongormCursor.Current()
    if current != nil {
        // Use current
    }
}
if err := mongormCursor.Err(); err != nil {
    // Handle error
}

func (*MongORMCursor[T]) Err added in v1.0.5

func (c *MongORMCursor[T]) Err() error

Err returns the most recent cursor error observed by Next or All.

func (*MongORMCursor[T]) Next

func (c *MongORMCursor[T]) Next(ctx context.Context) bool

Next advances the cursor to the next document and decodes it into a new MongORM instance. It returns false when there are no more documents to read or when an error occurs. Call Err to inspect the last cursor error after iteration ends. The caller is responsible for closing the cursor when done. The context can be used to cancel the operation if needed.

Example usage:

for mongormCursor.Next(ctx) {
    current := mongormCursor.Current()
    if current != nil {
        // Use current
    }
}

type MongORMInfo

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

MongORMInfo holds the internal information for a MongORM instance, including database and collection references, as well as field mappings. This struct is used internally by the MongORM instance to manage its connection and schema information.

> NOTE: This struct is not intended for public use.

type MongORMOperations

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

MongORMOperations holds the accumulated operations for a MongORM instance, including query filters, update documents, and other operation-specific information. This struct is used internally by the MongORM instance to manage the state of ongoing operations.

> NOTE: This struct is not intended for public use.

type MongORMOptions

type MongORMOptions struct {
	Timestamps     bool          `json:"-"`
	CollectionName *string       `json:"-"`
	DatabaseName   *string       `json:"-"`
	MongoClient    *mongo.Client `json:"-"`
}

MongORMOptions holds the configuration options for a MongORM instance, including settings for timestamps, collection and database names, and the MongoDB client. This struct is used to customize the behavior of the MongORM instance when connecting to the database and performing operations.

Example usage:

type ToDo struct {
  Text *string `bson:"text"`
}
options := &mongorm.MongORMOptions{
    Timestamps: true,
    CollectionName: ptr("todos"),
    DatabaseName: ptr("mydb"),
    MongoClient: myMongoClient,
}
orm := mongorm.FromOptions(&ToDo{}, options)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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