nosql

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CloseAll

func CloseAll(ctx context.Context) error

CloseAll closes all registered NoSQL connections.

func Register

func Register(name string, driver Driver)

Register registers a named NoSQL connection.

nosql.Register("mongo", mongoDriver)
nosql.Register("dynamo", dynamoDriver)

Types

type BaseDocument

type BaseDocument = Model

BaseDocument is an alias for Model. Deprecated: use nosql.Model instead.

type Builder

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

Builder is a fluent query builder for NoSQL collections.

func Query

func Query(connectionName, collectionName string) *Builder

Query starts a new query builder on a registered connection and collection.

nosql.Query("mongo", "users").Where("active", true).Get(ctx, &users)

func QueryOn

func QueryOn(driver Driver, collectionName string) *Builder

QueryOn starts a query builder on a specific driver instance.

nosql.QueryOn(mongoDriver, "users").Where("role", "admin").Get(ctx, &users)

func (*Builder) Aggregate

func (b *Builder) Aggregate(ctx context.Context, pipeline any, dest any) error

Aggregate runs an aggregation pipeline on the collection.

func (*Builder) Count

func (b *Builder) Count(ctx context.Context) (int64, error)

Count returns the number of matching documents.

func (*Builder) Delete

func (b *Builder) Delete(ctx context.Context) (*DeleteResult, error)

Delete deletes the first document matching the current filters.

func (*Builder) DeleteMany

func (b *Builder) DeleteMany(ctx context.Context) (*DeleteResult, error)

DeleteMany deletes all documents matching the current filters.

func (*Builder) Distinct

func (b *Builder) Distinct(ctx context.Context, field string) ([]any, error)

Distinct returns distinct values for a field matching current filters.

func (*Builder) Exclude

func (b *Builder) Exclude(fields ...string) *Builder

Exclude specifies which fields to exclude from results.

Exclude("password", "internal_notes")

func (*Builder) Exists

func (b *Builder) Exists(ctx context.Context) (bool, error)

Exists returns true if any matching document exists.

func (*Builder) FindByID

func (b *Builder) FindByID(ctx context.Context, id any, dest any) error

FindByID finds a single document by ID.

func (*Builder) First

func (b *Builder) First(ctx context.Context, dest any) error

First returns the first matching document.

func (*Builder) Get

func (b *Builder) Get(ctx context.Context, dest any) error

Get executes the query and decodes all matching documents into dest.

func (*Builder) Insert

func (b *Builder) Insert(ctx context.Context, doc any) (*InsertResult, error)

Insert inserts a single document.

func (*Builder) InsertMany

func (b *Builder) InsertMany(ctx context.Context, docs []any) (*InsertManyResult, error)

InsertMany inserts multiple documents.

func (*Builder) Latest

func (b *Builder) Latest(field ...string) *Builder

Latest sorts by a field descending (default: "created_at").

func (*Builder) Limit

func (b *Builder) Limit(n int64) *Builder

Limit limits the number of results.

func (*Builder) Oldest

func (b *Builder) Oldest(field ...string) *Builder

Oldest sorts by a field ascending (default: "created_at").

func (*Builder) OrWhere

func (b *Builder) OrWhere(conditions ...Filter) *Builder

OrWhere is not natively supported by all NoSQL backends but can be expressed with $or in MongoDB. This builds an $or clause.

OrWhere(nosql.Filter{"status": "active"}, nosql.Filter{"role": "admin"})

func (*Builder) Paginate

func (b *Builder) Paginate(ctx context.Context, dest any, page, perPage int64) (*NoSQLPaginator, error)

Paginate returns paginated results with metadata.

func (*Builder) Select

func (b *Builder) Select(fields ...string) *Builder

Select specifies which fields to include in results.

Select("name", "email", "age")

func (*Builder) Skip

func (b *Builder) Skip(n int64) *Builder

Skip skips N documents (for pagination).

func (*Builder) Sort

func (b *Builder) Sort(field string, order SortOrder) *Builder

Sort adds a sort order for a field.

Sort("created_at", nosql.Descending).Sort("name", nosql.Ascending)

func (*Builder) Update

func (b *Builder) Update(ctx context.Context, update any) (*UpdateResult, error)

Update updates the first document matching the current filters.

func (*Builder) UpdateMany

func (b *Builder) UpdateMany(ctx context.Context, update any) (*UpdateResult, error)

UpdateMany updates all documents matching the current filters.

func (*Builder) Upsert

func (b *Builder) Upsert(ctx context.Context, doc any) (*UpdateResult, error)

Upsert inserts or updates a document matching the current filters.

func (*Builder) Where

func (b *Builder) Where(field string, args ...any) *Builder

Where adds an equality filter. Supports multiple call patterns:

Where("name", "Alice")            → {name: "Alice"}
Where("age", ">=", 21)            → {age: {$gte: 21}}
Where("status", "in", []string{"active", "pending"})

func (*Builder) WhereBetween

func (b *Builder) WhereBetween(field string, min, max any) *Builder

WhereBetween adds a range filter (inclusive).

WhereBetween("age", 18, 30)

func (*Builder) WhereExists

func (b *Builder) WhereExists(field string, exists bool) *Builder

WhereExists adds an $exists filter.

WhereExists("deletedAt", false)  → documents without deletedAt field

func (*Builder) WhereIn

func (b *Builder) WhereIn(field string, values ...any) *Builder

WhereIn adds a $in filter.

WhereIn("status", "active", "pending", "review")

func (*Builder) WhereNotIn

func (b *Builder) WhereNotIn(field string, values ...any) *Builder

WhereNotIn adds a $nin filter.

func (*Builder) WhereNotNull

func (b *Builder) WhereNotNull(field string) *Builder

WhereNotNull matches documents where a field exists and is not null.

func (*Builder) WhereNull

func (b *Builder) WhereNull(field string) *Builder

WhereNull matches documents where a field is null or missing.

func (*Builder) WhereRaw

func (b *Builder) WhereRaw(field string, raw Document) *Builder

WhereRaw sets a raw filter map for the given field, allowing full control over the MongoDB query operators.

WhereRaw("location", nosql.Document{"$near": ...})

func (*Builder) WhereRegex

func (b *Builder) WhereRegex(field, pattern string) *Builder

WhereRegex matches documents where a field matches a regex pattern.

type Collection

type Collection interface {
	// Name returns the collection name.
	Name() string

	// InsertOne inserts a single document and returns a Result.
	InsertOne(ctx context.Context, doc any) (*InsertResult, error)

	// InsertMany inserts multiple documents.
	InsertMany(ctx context.Context, docs []any) (*InsertManyResult, error)

	// FindOne finds a single document matching the filter and decodes into dest.
	FindOne(ctx context.Context, filter Filter, dest any) error

	// Find finds all documents matching the filter and decodes into dest (slice).
	Find(ctx context.Context, filter Filter, dest any, opts ...FindOption) error

	// FindByID finds a document by its ID (string or primitive).
	FindByID(ctx context.Context, id any, dest any) error

	// Count returns the number of documents matching the filter.
	Count(ctx context.Context, filter Filter) (int64, error)

	// Exists returns true if any document matches the filter.
	Exists(ctx context.Context, filter Filter) (bool, error)

	// UpdateOne updates a single document matching the filter.
	UpdateOne(ctx context.Context, filter Filter, update any) (*UpdateResult, error)

	// UpdateMany updates all documents matching the filter.
	UpdateMany(ctx context.Context, filter Filter, update any) (*UpdateResult, error)

	// UpdateByID updates a document by its ID.
	UpdateByID(ctx context.Context, id any, update any) (*UpdateResult, error)

	// Upsert inserts or updates a document matching the filter.
	Upsert(ctx context.Context, filter Filter, doc any) (*UpdateResult, error)

	// DeleteOne deletes a single document matching the filter.
	DeleteOne(ctx context.Context, filter Filter) (*DeleteResult, error)

	// DeleteMany deletes all documents matching the filter.
	DeleteMany(ctx context.Context, filter Filter) (*DeleteResult, error)

	// DeleteByID deletes a document by its ID.
	DeleteByID(ctx context.Context, id any) (*DeleteResult, error)

	// Aggregate runs an aggregation pipeline.
	Aggregate(ctx context.Context, pipeline any, dest any) error

	// Distinct returns distinct values for a field.
	Distinct(ctx context.Context, field string, filter Filter) ([]any, error)

	// CreateIndex creates an index on the collection.
	CreateIndex(ctx context.Context, keys Document, opts ...IndexOption) (string, error)

	// DropIndex drops an index by name.
	DropIndex(ctx context.Context, name string) error

	// Drop drops the entire collection.
	Drop(ctx context.Context) error
}

Collection provides CRUD operations on a document collection.

type DeleteResult

type DeleteResult struct {
	DeletedCount int64
}

DeleteResult is returned by Delete operations.

type Document

type Document map[string]any

Document is a generic document representation.

type Driver

type Driver interface {
	// Name returns the driver name (e.g. "mongodb", "dynamodb", "redis").
	Name() string

	// Collection returns a Collection handle for the given name.
	Collection(name string) Collection

	// Ping checks if the connection is alive.
	Ping(ctx context.Context) error

	// Close closes the connection.
	Close(ctx context.Context) error

	// Database returns a driver scoped to a specific database (for multi-DB engines like MongoDB).
	Database(name string) Driver

	// DropDatabase drops the entire database (use with caution).
	DropDatabase(ctx context.Context) error
}

Driver is the top-level NoSQL driver (one per database connection).

func Connection

func Connection(name string) Driver

Connection returns a registered NoSQL driver by name.

func MustConnection

func MustConnection(name string) Driver

MustConnection returns a registered driver or panics.

type Filter

type Filter map[string]any

Filter is a key-value map used for query conditions.

type FindOption

type FindOption struct {
	// Sort specifies the sort order.
	Sort Sort

	// Limit limits the number of documents returned.
	Limit int64

	// Skip skips a number of documents.
	Skip int64

	// Projection selects which fields to return (1 = include, 0 = exclude).
	Projection Document
}

FindOption modifies Find behavior.

type IndexOption

type IndexOption struct {
	// Unique makes the index unique.
	Unique bool

	// Name overrides the default index name.
	Name string

	// ExpireAfterSeconds sets a TTL (for TTL indexes).
	ExpireAfterSeconds *int32

	// Sparse creates a sparse index (only indexes documents that have the indexed field).
	Sparse bool
}

IndexOption modifies CreateIndex behavior.

type InsertManyResult

type InsertManyResult struct {
	InsertedIDs []any
}

InsertManyResult is returned by InsertMany.

type InsertResult

type InsertResult struct {
	InsertedID any
}

InsertResult is returned by InsertOne.

type Model

type Model struct {
	ID        string     `bson:"_id,omitempty" json:"id"`
	CreatedAt time.Time  `bson:"created_at"   json:"created_at"`
	UpdatedAt time.Time  `bson:"updated_at"   json:"updated_at"`
	DeletedAt *time.Time `bson:"deleted_at,omitempty" json:"deleted_at,omitempty"`
}

Model is the base model for NoSQL documents. Embed it in your structs for standard fields — mirrors database.Model on the SQL side so the pattern stays consistent across your app.

type Post struct {
    nosql.Model
    Title string
}

type MongoCollection

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

MongoCollection implements nosql.Collection using MongoDB.

func (*MongoCollection) Aggregate

func (c *MongoCollection) Aggregate(ctx context.Context, pipeline any, dest any) error

func (*MongoCollection) Count

func (c *MongoCollection) Count(ctx context.Context, filter Filter) (int64, error)

func (*MongoCollection) CreateIndex

func (c *MongoCollection) CreateIndex(ctx context.Context, keys Document, opts ...IndexOption) (string, error)

func (*MongoCollection) DeleteByID

func (c *MongoCollection) DeleteByID(ctx context.Context, id any) (*DeleteResult, error)

func (*MongoCollection) DeleteMany

func (c *MongoCollection) DeleteMany(ctx context.Context, filter Filter) (*DeleteResult, error)

func (*MongoCollection) DeleteOne

func (c *MongoCollection) DeleteOne(ctx context.Context, filter Filter) (*DeleteResult, error)

func (*MongoCollection) Distinct

func (c *MongoCollection) Distinct(ctx context.Context, field string, filter Filter) ([]any, error)

func (*MongoCollection) Drop

func (c *MongoCollection) Drop(ctx context.Context) error

func (*MongoCollection) DropIndex

func (c *MongoCollection) DropIndex(ctx context.Context, name string) error

func (*MongoCollection) Exists

func (c *MongoCollection) Exists(ctx context.Context, filter Filter) (bool, error)

func (*MongoCollection) Find

func (c *MongoCollection) Find(ctx context.Context, filter Filter, dest any, opts ...FindOption) error

func (*MongoCollection) FindByID

func (c *MongoCollection) FindByID(ctx context.Context, id any, dest any) error

func (*MongoCollection) FindOne

func (c *MongoCollection) FindOne(ctx context.Context, filter Filter, dest any) error

func (*MongoCollection) InsertMany

func (c *MongoCollection) InsertMany(ctx context.Context, docs []any) (*InsertManyResult, error)

func (*MongoCollection) InsertOne

func (c *MongoCollection) InsertOne(ctx context.Context, doc any) (*InsertResult, error)

func (*MongoCollection) Name

func (c *MongoCollection) Name() string

func (*MongoCollection) UpdateByID

func (c *MongoCollection) UpdateByID(ctx context.Context, id any, update any) (*UpdateResult, error)

func (*MongoCollection) UpdateMany

func (c *MongoCollection) UpdateMany(ctx context.Context, filter Filter, update any) (*UpdateResult, error)

func (*MongoCollection) UpdateOne

func (c *MongoCollection) UpdateOne(ctx context.Context, filter Filter, update any) (*UpdateResult, error)

func (*MongoCollection) Upsert

func (c *MongoCollection) Upsert(ctx context.Context, filter Filter, doc any) (*UpdateResult, error)

type MongoConfig

type MongoConfig struct {
	// URI is the MongoDB connection string (e.g. "mongodb://localhost:27017").
	URI string

	// Database is the default database name.
	Database string

	// ConnectTimeout is the connection timeout (default: 10s).
	ConnectTimeout time.Duration

	// MaxPoolSize sets the max number of connections in the pool (default: 100).
	MaxPoolSize uint64

	// MinPoolSize sets the min connections to keep in the pool.
	MinPoolSize uint64
}

MongoConfig configures a MongoDB connection.

type MongoDriver

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

MongoDriver wraps the official MongoDB Go driver.

func ConnectMongo

func ConnectMongo(ctx context.Context, cfg MongoConfig) (*MongoDriver, error)

ConnectMongo creates a new MongoDB connection.

func (*MongoDriver) Client

func (d *MongoDriver) Client() *mongo.Client

Client returns the underlying *mongo.Client for advanced usage.

func (*MongoDriver) Close

func (d *MongoDriver) Close(ctx context.Context) error

func (*MongoDriver) Collection

func (d *MongoDriver) Collection(name string) Collection

func (*MongoDriver) DB

func (d *MongoDriver) DB() *mongo.Database

DB returns the underlying *mongo.Database for advanced usage.

func (*MongoDriver) Database

func (d *MongoDriver) Database(name string) Driver

func (*MongoDriver) DropDatabase

func (d *MongoDriver) DropDatabase(ctx context.Context) error

func (*MongoDriver) Name

func (d *MongoDriver) Name() string

func (*MongoDriver) Ping

func (d *MongoDriver) Ping(ctx context.Context) error

type NoSQLPaginator

type NoSQLPaginator struct {
	Data        any   `json:"data"`
	Total       int64 `json:"total"`
	PerPage     int64 `json:"per_page"`
	CurrentPage int64 `json:"current_page"`
	LastPage    int64 `json:"last_page"`
}

NoSQLPaginator holds paginated NoSQL results.

func (*NoSQLPaginator) HasMore

func (p *NoSQLPaginator) HasMore() bool

HasMore returns true if there are more pages.

type Sort

type Sort map[string]SortOrder

Sort represents sort options.

type SortOrder

type SortOrder int

SortOrder represents sort direction.

const (
	Ascending  SortOrder = 1
	Descending SortOrder = -1
)

type TimestampedDocument

type TimestampedDocument = Model

TimestampedDocument is an alias for Model. Deprecated: use nosql.Model instead.

type UpdateResult

type UpdateResult struct {
	MatchedCount  int64
	ModifiedCount int64
	UpsertedCount int64
	UpsertedID    any
}

UpdateResult is returned by Update operations.

Jump to

Keyboard shortcuts

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