Documentation
¶
Index ¶
- Variables
- func AddToSetUpdateFromPairs(pairs ...FieldValuePair) bson.M
- func AggregateAs[T any, R any](m *MongORM[T], ctx context.Context, pipeline bson.A, ...) ([]R, error)
- func AggregatePipelineAs[T any, R any](m *MongORM[T], ctx context.Context, ...) ([]R, error)
- func Asc(field Field) bson.E
- func Bool(b bool) *bool
- func BoolVal(b *bool) bool
- func Decimal128(d bson.Decimal128) *bson.Decimal128
- func Decimal128Val(d *bson.Decimal128) bson.Decimal128
- func Desc(field Field) bson.E
- func DistinctAs[V any](values []any) ([]V, error)
- func DistinctFieldAs[T any, V any](m *MongORM[T], ctx context.Context, field Field, ...) ([]V, error)
- func Facet(alias AggregateAlias, pipeline bson.A) bson.E
- func FieldRef(field Field) string
- func FieldsOf[T any, F any]() F
- func FilterBy(field Field, value any) bson.M
- func FindAllAs[T any, R any](m *MongORM[T], ctx context.Context, ...) ([]R, error)
- func FindOneAs[T any, R any](m *MongORM[T], ctx context.Context, ...) (*R, error)
- func Float64(f float64) *float64
- func Float64Val(f *float64) float64
- func Geo2D(field Field) bson.E
- func Geo2DSphere(field Field) bson.E
- func IncUpdateFromPairs(pairs ...FieldValuePair) bson.M
- func IndexModelFromKeys(keys ...bson.E) mongo.IndexModel
- func Int64(i int64) *int64
- func Int64Val(i *int64) int64
- func IsTransactionUnsupported(err error) bool
- func NamedIndexModelFromKeys(name string, keys ...bson.E) mongo.IndexModel
- func NestedFieldsOf[T any, F any](parent Field) F
- func NewClient(connectionString string) (*mongo.Client, error)
- func PopUpdateFromPairs(pairs ...FieldValuePair) bson.M
- func PullUpdateFromPairs(pairs ...FieldValuePair) bson.M
- func PushUpdateFromPairs(pairs ...FieldValuePair) bson.M
- func SetOnInsertUpdateFromPairs(pairs ...FieldValuePair) bson.M
- func SetUpdateFromPairs(pairs ...FieldValuePair) bson.M
- func String(s string) *string
- func StringVal(s *string) string
- func Text(field Field) bson.E
- func Timestamp(t time.Time) *time.Time
- func TimestampVal(t *time.Time) time.Time
- func UniqueIndexModelFromKeys(keys ...bson.E) mongo.IndexModel
- func UnsetUpdateFromFields(fields ...Field) bson.M
- type AfterCreateHook
- type AfterDeleteHook
- type AfterFinalizeHook
- type AfterFindHook
- type AfterSaveHook
- type AfterUpdateHook
- type AggregateAlias
- type BeforeCreateHook
- type BeforeDeleteHook
- type BeforeFinalizeHook
- type BeforeFindHook
- type BeforeSaveHook
- type BeforeUpdateHook
- type BulkWriteBuilder
- func (b *BulkWriteBuilder[T]) DeleteMany(filter bson.M) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) DeleteManyBy(field Field, value any) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) DeleteOne(filter bson.M) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) DeleteOneBy(field Field, value any) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) InsertOne(document *T) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) Models() []mongo.WriteModel
- func (b *BulkWriteBuilder[T]) ReplaceOne(filter bson.M, replacement *T, upsert bool) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) ReplaceOneBy(field Field, value any, replacement *T, upsert bool) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) UpdateMany(filter bson.M, update bson.M, upsert bool) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) UpdateManyBy(field Field, value any, update bson.M, upsert bool) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) UpdateOne(filter bson.M, update bson.M, upsert bool) *BulkWriteBuilder[T]
- func (b *BulkWriteBuilder[T]) UpdateOneBy(field Field, value any, update bson.M, upsert bool) *BulkWriteBuilder[T]
- type Field
- func FieldPath(base Field, suffix string) Field
- func Indexed(field Field, index int) Field
- func NewFieldFromSchemaType(t reflect.Type, name string) (Field, bool)
- func NewFieldFromType(t reflect.Type, name string) Field
- func Positional(field Field) Field
- func PositionalAll(field Field) Field
- func PositionalFiltered(field Field, identifier string) Field
- func RawField(path string) Field
- type FieldValuePair
- type GeoLineString
- type GeoPoint
- type GeoPolygon
- type ModelTags
- type MongORM
- func (m *MongORM[T]) AddFieldStage(alias AggregateAlias, value any) *MongORM[T]
- func (m *MongORM[T]) AddFieldsStage(fields bson.M) *MongORM[T]
- func (m *MongORM[T]) AddToSetData(field any, value any) *MongORM[T]
- func (m *MongORM[T]) AddToSetEachData(field any, values []any) *MongORM[T]
- func (m *MongORM[T]) After(field Field, cursor any) *MongORM[T]
- func (m *MongORM[T]) Aggregate(ctx context.Context, pipeline bson.A, ...) (*MongORMCursor[T], error)
- func (m *MongORM[T]) AggregatePipeline(ctx context.Context, opts ...options.Lister[options.AggregateOptions]) (*MongORMCursor[T], error)
- func (m *MongORM[T]) AggregatePipelineRaw(ctx context.Context, opts ...options.Lister[options.AggregateOptions]) (*mongo.Cursor, error)
- func (m *MongORM[T]) AggregateRaw(ctx context.Context, pipeline bson.A, ...) (*mongo.Cursor, error)
- func (m *MongORM[T]) Before(field Field, cursor any) *MongORM[T]
- func (m *MongORM[T]) BulkWrite(ctx context.Context, models []mongo.WriteModel, ...) (*mongo.BulkWriteResult, error)
- func (m *MongORM[T]) BulkWriteInTransaction(ctx context.Context, models []mongo.WriteModel, ...) (*mongo.BulkWriteResult, error)
- func (m *MongORM[T]) Count(ctx context.Context, opts ...options.Lister[options.CountOptions]) (int64, error)
- func (m *MongORM[T]) DecData(field any, value int64) *MongORM[T]
- func (m *MongORM[T]) DecFloat64Data(field any, value float64) *MongORM[T]
- func (m *MongORM[T]) Delete(ctx context.Context) error
- func (m *MongORM[T]) DeleteMulti(ctx context.Context, opts ...options.Lister[options.DeleteManyOptions]) (*mongo.DeleteResult, error)
- func (m *MongORM[T]) Distinct(ctx context.Context, field Field, ...) ([]any, error)
- func (m *MongORM[T]) DistinctBool(ctx context.Context, field Field, ...) ([]bool, error)
- func (m *MongORM[T]) DistinctFloat64(ctx context.Context, field Field, ...) ([]float64, error)
- func (m *MongORM[T]) DistinctInt64(ctx context.Context, field Field, ...) ([]int64, error)
- func (m *MongORM[T]) DistinctObjectIDs(ctx context.Context, field Field, ...) ([]bson.ObjectID, error)
- func (m *MongORM[T]) DistinctStrings(ctx context.Context, field Field, ...) ([]string, error)
- func (m *MongORM[T]) DistinctTimes(ctx context.Context, field Field, ...) ([]time.Time, error)
- func (m *MongORM[T]) Document() *T
- func (m *MongORM[T]) Ensure2DSphereIndex(ctx context.Context, field Field, ...) (string, error)
- func (m *MongORM[T]) EnsureGeoDefaults(ctx context.Context, geoField Field, supportingKeys []bson.E, ...) ([]string, error)
- func (m *MongORM[T]) EnsureIndex(ctx context.Context, model mongo.IndexModel, ...) (string, error)
- func (m *MongORM[T]) EnsureIndexes(ctx context.Context, models []mongo.IndexModel, ...) ([]string, error)
- func (m *MongORM[T]) FacetStage(facets bson.M) *MongORM[T]
- func (m *MongORM[T]) FacetStageEntries(entries ...bson.E) *MongORM[T]
- func (m *MongORM[T]) Find(ctx context.Context, opts ...options.Lister[options.FindOneOptions]) error
- func (m *MongORM[T]) FindAll(ctx context.Context, opts ...options.Lister[options.FindOptions]) (*MongORMCursor[T], error)
- func (m *MongORM[T]) FindOneAndUpdate(ctx context.Context, opts ...options.Lister[options.FindOneAndUpdateOptions]) error
- func (m *MongORM[T]) First(ctx context.Context, opts ...options.Lister[options.FindOneOptions]) error
- func (m *MongORM[T]) GetRawQuery() bson.M
- func (m *MongORM[T]) GetRawUpdate() bson.M
- func (m *MongORM[T]) GetResolvedRawQuery() (bson.M, error)
- func (m *MongORM[T]) GroupCountBy(field Field, as string) *MongORM[T]
- func (m *MongORM[T]) GroupCountByAlias(field Field, as AggregateAlias) *MongORM[T]
- func (m *MongORM[T]) GroupStage(group bson.M) *MongORM[T]
- func (m *MongORM[T]) GroupSumBy(groupBy Field, sumField Field, as string) *MongORM[T]
- func (m *MongORM[T]) GroupSumByAlias(groupBy Field, sumField Field, as AggregateAlias) *MongORM[T]
- func (m *MongORM[T]) IncData(field any, value any) *MongORM[T]
- func (m *MongORM[T]) IncFloat64Data(field any, value float64) *MongORM[T]
- func (m *MongORM[T]) IsModified(field any) bool
- func (m *MongORM[T]) JSON(doc *T) (map[string]any, error)
- func (m *MongORM[T]) Limit(value int64) *MongORM[T]
- func (m *MongORM[T]) LimitStage(limit int64) *MongORM[T]
- func (m *MongORM[T]) LookupByStage(from string, localField Field, foreignField Field, as AggregateAlias) *MongORM[T]
- func (m *MongORM[T]) LookupPipelineStage(from string, let bson.M, pipeline bson.A, as string) *MongORM[T]
- func (m *MongORM[T]) LookupStage(from string, localField string, foreignField string, as string) *MongORM[T]
- func (m *MongORM[T]) MatchBy(field Field, value any) *MongORM[T]
- func (m *MongORM[T]) MatchExpr(expr bson.M) *MongORM[T]
- func (m *MongORM[T]) MatchStage(match bson.M) *MongORM[T]
- func (m *MongORM[T]) MatchWhere() *MongORM[T]
- func (m *MongORM[T]) ModifiedFields() []Field
- func (m *MongORM[T]) ModifiedValue(field any) (oldValue any, newValue any, ok bool)
- func (m *MongORM[T]) OrWhere(expr bson.M) *MongORM[T]
- func (m *MongORM[T]) OrWhereAnd(exprs ...bson.M) *MongORM[T]
- func (m *MongORM[T]) OrWhereBy(field Field, value any) *MongORM[T]
- func (m *MongORM[T]) PaginateAfter(field Field, cursor any, size int64) *MongORM[T]
- func (m *MongORM[T]) PaginateBefore(field Field, cursor any, size int64) *MongORM[T]
- func (m *MongORM[T]) Pipeline(stages ...bson.M) *MongORM[T]
- func (m *MongORM[T]) PopData(field any, value int) *MongORM[T]
- func (m *MongORM[T]) PopFirstData(field any) *MongORM[T]
- func (m *MongORM[T]) PopLastData(field any) *MongORM[T]
- func (m *MongORM[T]) ProjectIncludeFields(fields ...Field) *MongORM[T]
- func (m *MongORM[T]) ProjectStage(project bson.M) *MongORM[T]
- func (m *MongORM[T]) Projection(value any) *MongORM[T]
- func (m *MongORM[T]) ProjectionExclude(fields ...Field) *MongORM[T]
- func (m *MongORM[T]) ProjectionInclude(fields ...Field) *MongORM[T]
- func (m *MongORM[T]) PullData(field any, value any) *MongORM[T]
- func (m *MongORM[T]) PushData(field any, value any) *MongORM[T]
- func (m *MongORM[T]) PushEachData(field any, values []any) *MongORM[T]
- func (m *MongORM[T]) ResetPipeline() *MongORM[T]
- func (m *MongORM[T]) Save(ctx context.Context, opts ...options.Lister[options.FindOneAndUpdateOptions]) error
- func (m *MongORM[T]) SaveMulti(ctx context.Context, opts ...options.Lister[options.UpdateManyOptions]) (*mongo.UpdateResult, error)
- func (m *MongORM[T]) Set(value *T) *MongORM[T]
- func (m *MongORM[T]) SetData(field any, value any) *MongORM[T]
- func (m *MongORM[T]) SetOnInsert(value *T) *MongORM[T]
- func (m *MongORM[T]) SetOnInsertData(field any, value any) *MongORM[T]
- func (m *MongORM[T]) Skip(value int64) *MongORM[T]
- func (m *MongORM[T]) SkipStage(skip int64) *MongORM[T]
- func (m *MongORM[T]) Sort(value any) *MongORM[T]
- func (m *MongORM[T]) SortAsc(field Field) *MongORM[T]
- func (m *MongORM[T]) SortBy(field Field, direction int) *MongORM[T]
- func (m *MongORM[T]) SortByStage(field Field, direction int) *MongORM[T]
- func (m *MongORM[T]) SortDesc(field Field) *MongORM[T]
- func (m *MongORM[T]) SortStage(sort any) *MongORM[T]
- func (m *MongORM[T]) Unset(value *T) *MongORM[T]
- func (m *MongORM[T]) UnsetData(field any) *MongORM[T]
- func (m *MongORM[T]) UnwindByStage(field Field) *MongORM[T]
- func (m *MongORM[T]) UnwindStage(path string) *MongORM[T]
- func (m *MongORM[T]) Where(expr bson.M) *MongORM[T]
- func (m *MongORM[T]) WhereAnd(exprs ...bson.M) *MongORM[T]
- func (m *MongORM[T]) WhereBy(field Field, value any) *MongORM[T]
- func (m *MongORM[T]) WithTransaction(ctx context.Context, fn func(txCtx context.Context) error, ...) error
- type MongORMCursor
- type MongORMInfo
- type MongORMOperations
- type MongORMOptions
Constants ¶
This section is empty.
Variables ¶
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 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 ¶
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 DistinctAs ¶
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 FieldsOf ¶
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 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
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
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 Geo2DSphere ¶
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 ¶
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 ¶
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 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
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 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 ¶
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 ¶
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 Timestamp ¶
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 ¶
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
UnsetUpdateFromFields builds an update document with $unset using schema fields.
Types ¶
type AfterCreateHook ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
type BeforeCreateHook ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Indexed ¶ added in v1.0.3
Indexed builds a field path for a specific array index. Example: Indexed(ToDoFields.Items, 2) => "items.2"
func NewFieldFromSchemaType ¶ added in v1.0.3
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 ¶
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
Positional builds a field path using MongoDB positional operator `$`. Example: Positional(ToDoFields.Items) => "items.$"
func PositionalAll ¶ added in v1.0.3
PositionalAll builds a field path using MongoDB all positional operator `$[]`. Example: PositionalAll(ToDoFields.Items) => "items.$[]"
func PositionalFiltered ¶ added in v1.0.3
PositionalFiltered builds a field path using MongoDB filtered positional operator `$[identifier]`. Example: PositionalFiltered(ToDoFields.Items, "item") => "items.$[item]"
type FieldValuePair ¶ added in v1.0.3
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 ¶
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 ¶
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 ¶
AddFieldsStage appends a $addFields stage.
func (*MongORM[T]) AddToSetData ¶ added in v1.0.8
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
AddToSetEachData appends multiple values uniquely using MongoDB's $addToSet + $each syntax.
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]) 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
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
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 ¶
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 ¶
FacetStage appends a $facet stage.
func (*MongORM[T]) FacetStageEntries ¶
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
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
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
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 ¶
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 ¶
GroupStage appends a $group stage.
func (*MongORM[T]) GroupSumBy ¶
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
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
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 (*MongORM[T]) JSON ¶
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 ¶
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 ¶
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]) MatchExpr ¶
MatchExpr appends a $match stage from an expression built by field operators such as Eq/Gt/Reg.
func (*MongORM[T]) MatchStage ¶
MatchStage appends a $match stage.
func (*MongORM[T]) MatchWhere ¶
MatchWhere appends a $match stage from accumulated Where()/WhereBy() filters.
func (*MongORM[T]) ModifiedFields ¶ added in v1.0.3
func (*MongORM[T]) ModifiedValue ¶ added in v1.0.13
func (*MongORM[T]) OrWhere ¶ added in v1.0.6
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
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
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 ¶
PaginateAfter applies keyset pagination in ascending order for the given field.
func (*MongORM[T]) PaginateBefore ¶
PaginateBefore applies keyset pagination in descending order for the given field.
func (*MongORM[T]) Pipeline ¶
Pipeline appends one or more aggregation stages to the current aggregate pipeline.
func (*MongORM[T]) PopData ¶ added in v1.0.8
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
PopFirstData removes the first element from an array field.
func (*MongORM[T]) PopLastData ¶ added in v1.0.8
PopLastData removes the last element from an array field.
func (*MongORM[T]) ProjectIncludeFields ¶
ProjectIncludeFields appends a $project stage that includes only the provided fields.
func (*MongORM[T]) ProjectStage ¶
ProjectStage appends a $project stage.
func (*MongORM[T]) Projection ¶
Projection sets the fields returned by find operations. Example: bson.M{"text": 1, "count": 1}
func (*MongORM[T]) ProjectionExclude ¶ added in v1.0.3
ProjectionExclude sets projection to exclude the given schema fields.
func (*MongORM[T]) ProjectionInclude ¶ added in v1.0.3
ProjectionInclude sets projection to include only the given schema fields.
func (*MongORM[T]) PullData ¶ added in v1.0.8
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
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
PushEachData appends multiple values using MongoDB's $push + $each syntax.
func (*MongORM[T]) ResetPipeline ¶
ResetPipeline clears accumulated aggregation stages.
func (*MongORM[T]) Save ¶
func (m *MongORM[T]) Save( ctx context.Context, opts ...options.Lister[options.FindOneAndUpdateOptions], ) error
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 ¶
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
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
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
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 ¶
Skip sets the number of documents to skip before returning results for find operations.
func (*MongORM[T]) Sort ¶
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]) SortBy ¶ added in v1.0.3
SortBy sets sort using a schema field and direction. Use 1 for ascending and -1 for descending.
func (*MongORM[T]) SortByStage ¶
SortByStage appends a $sort stage using a schema field and direction. Use 1 for ascending and -1 for descending.
func (*MongORM[T]) Unset ¶
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
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
UnwindByStage appends a $unwind stage using a schema field path.
func (*MongORM[T]) UnwindStage ¶
UnwindStage appends a $unwind stage.
func (*MongORM[T]) Where ¶
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
WhereAnd adds one or more query expressions under the $and operator. Use this when explicit $and grouping is required.
func (*MongORM[T]) WhereBy ¶
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)
Source Files
¶
- aggregate_builder.go
- bulk_write.go
- connection.go
- cursor.go
- db_multi_operations.go
- db_single_operations.go
- errors.go
- field.go
- field_path.go
- geo_types.go
- hooks.go
- indexes.go
- modified_tracking.go
- mongorm.go
- mongorm_private.go
- operation.go
- options.go
- output.go
- private_operations.go
- projection.go
- query.go
- tags.go
- timestamp.go
- transactions.go
- types.go
- utils.go
- versioning.go
- where.go