mongodb

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: GPL-3.0 Imports: 12 Imported by: 0

Documentation

Overview

Package mongodb provides MongoDB client and document helpers.

New code should use explicit client ownership and core-owned document contracts:

import "github.com/InsideGallery/core/db/mongodb"

store := mongodb.NewClientStore(nil)
client, err := store.GetOrCreate(config)

Prefer DocumentStore with FindOptions, CountOptions, InsertOptions, UpdateOptions, DeleteOptions, DocumentResult, and WriteResult for application boundaries that should not expose MongoDB SDK result types.

Compatibility: package-level Set, Get, and Default remain available for existing consumers. Prefer NewMongoClient or ClientStore.GetOrCreate with explicit configuration in new code.

Index

Constants

View Source
const EnvPrefix = "MONGO"

EnvPrefix environment prefix for mongodb config

View Source
const (
	TwoPrecision = 2
)

Variables

View Source
var (
	ErrConnectionIsNotSet = errors.New("connection is not set")
)

All kind of errors for mongo

View Source
var ErrDocumentTargetIsNotSet = errors.New("document target is not set")

ErrDocumentTargetIsNotSet reports a missing decode target for document reads.

View Source
var ErrFilterKeyType = errors.New("filter key must be a string")

ErrFilterKeyType reports a non-string filter key.

View Source
var ErrFilterPairCount = errors.New("filter pairs must contain key and value")

ErrFilterPairCount reports an odd key/value filter input.

Functions

func Clone

func Clone(oldObj interface{}) interface{}

func GetBsonD deprecated

func GetBsonD(keyValue ...interface{}) bson.D

GetBsonD return bson.D object based on values

Deprecated: use NewFilter, NewDocument, FilterFromPairs, DocumentFromPairs, or NewSort.

func NewSort added in v1.1.0

func NewSort(fields ...SortField) any

NewSort creates a MongoDB-compatible sort document without exposing BSON types in the public signature.

func Set deprecated

func Set(r *MongoClient)

Set global client

Deprecated: use ClientStore.Set on an explicit store.

Types

type Client deprecated

type Client interface {
	FindOne(
		ctx context.Context,
		collection string, value interface{}, filter interface{}, opts ...*options.FindOneOptions) error
	Find(
		ctx context.Context,
		collection string,
		value interface{},
		filter interface{},
		opts ...*options.FindOptions,
	) ([]interface{}, error)
	FindOneByID(
		ctx context.Context,
		collection string,
		value interface{},
		id interface{},
		opts ...*options.FindOneOptions,
	) error
	CountDocuments(
		ctx context.Context,
		collection string,
		filter interface{},
		opts ...*options.CountOptions,
	) (int64, error)
	Aggregate(
		ctx context.Context,
		collection string,
		value interface{},
		pipeline interface{},
		opts ...*options.AggregateOptions,
	) ([]interface{}, error)
	InsertOne(
		ctx context.Context,
		collection string,
		value interface{},
		opts ...*options.InsertOneOptions,
	) error
	UpsertOne(
		ctx context.Context,
		collection string,
		update interface{},
		filter interface{},
		opts ...*options.UpdateOptions,
	) error
	UpsertMany(
		ctx context.Context,
		collection string,
		keys []interface{},
		documents []interface{},
	) error
	UpsertManyByFilter(
		ctx context.Context,
		collection string,
		filterBy string,
		keys []interface{},
		documents []interface{},
	) error
	UpdateByObject(
		ctx context.Context,
		collection string,
		value interface{},
		filter interface{},
		opts ...*options.UpdateOptions,
	) error
	DeleteOne(ctx context.Context, collection string, filter interface{}, opts ...*options.DeleteOptions) error
	DeleteMany(ctx context.Context, collection string, filter interface{}, opts ...*options.DeleteOptions) error
	Drop(ctx context.Context, collection string) error
	InsertMany(ctx context.Context, collection string, documents []interface{}, opts ...*options.InsertManyOptions) error
	Collection(name string, opts ...*options.CollectionOptions) *mongo.Collection
	Database(name string, opts ...*options.DatabaseOptions) *mongo.Database
	WithDB(name string) Client
	Connection() *mongo.Client
	BatchUpdateByID(ctx context.Context, collection string, data map[interface{}]interface{}) error
	DeleteCollection(ctx context.Context, name string) error
}

Client is the legacy MongoDB SDK-shaped client contract.

Deprecated: use DocumentStore and core-owned option/result types for new code.

type ClientStore added in v1.1.0

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

ClientStore owns a MongoDB client for explicit application composition.

func NewClientStore added in v1.1.0

func NewClientStore(client *MongoClient) *ClientStore

NewClientStore creates a MongoDB client store with an optional existing client.

func (*ClientStore) Close added in v1.1.0

func (s *ClientStore) Close(ctx context.Context) error

Close disconnects the stored MongoDB client and clears this store.

func (*ClientStore) Get added in v1.1.0

func (s *ClientStore) Get() (*MongoClient, error)

Get returns the MongoDB client from this store.

func (*ClientStore) GetOrCreate added in v1.1.0

func (s *ClientStore) GetOrCreate(config *ConnectionConfig) (*MongoClient, error)

GetOrCreate returns or creates a MongoDB client from explicit config.

func (*ClientStore) Set added in v1.1.0

func (s *ClientStore) Set(client *MongoClient)

Set stores a MongoDB client in this store.

type ConnectionConfig

type ConnectionConfig struct {
	Hosts         []string `env:"_HOSTS" envDefault:"localhost:27017"`
	User          string   `env:"_USER" envDefault:""`
	Pass          string   `env:"_PASS" envDefault:""`
	Scheme        string   `env:"_SCHEME" envDefault:"mongodb"`
	Database      string   `env:"_DATABASE" envDefault:"default"`
	Args          string   `env:"_ARGS" envDefault:""`
	Mode          string   `env:"_MODE" envDefault:"secondarypreferred"`
	RetryWrites   bool     `env:"_RETRYWRITES" envDefault:"false"`
	AuthMechanism string   `env:"_AUTH_MECHANISM" envDefault:"SCRAM-SHA-256"`
	AuthSource    string   `env:"_AUTH_SOURCE" envDefault:""`
}

ConnectionConfig contains required data for mongo

func GetConnectionConfigFromEnv

func GetConnectionConfigFromEnv() (*ConnectionConfig, error)

GetConnectionConfigFromEnv return mongodb configs bases on environment variables

func (*ConnectionConfig) GetDSN

func (c *ConnectionConfig) GetDSN() string

type CountOptions added in v1.1.0

type CountOptions struct {
	Collection string
	Filter     any
}

CountOptions is the core-owned input for MongoDB count operations.

type DeleteOptions added in v1.1.0

type DeleteOptions struct {
	Collection string
	Filter     any
	Many       bool
}

DeleteOptions is the core-owned input for MongoDB delete operations.

type Document added in v1.1.0

type Document map[string]any

Document is a core-owned MongoDB document shape.

func DocumentFromPairs added in v1.1.0

func DocumentFromPairs(keyValue ...any) (Document, error)

DocumentFromPairs creates a core-owned MongoDB document from key/value pairs.

func NewDocument added in v1.1.0

func NewDocument(fields ...Field) Document

NewDocument creates a core-owned MongoDB document.

type DocumentResult added in v1.1.0

type DocumentResult struct {
	Found     bool
	Document  any
	Documents []any
	Count     int64
}

DocumentResult is the core-owned result for MongoDB read operations.

type DocumentStore added in v1.1.0

type DocumentStore interface {
	FindOneDocument(ctx context.Context, options FindOptions) (DocumentResult, error)
	FindDocuments(ctx context.Context, options FindOptions) (DocumentResult, error)
	Count(ctx context.Context, options CountOptions) (DocumentResult, error)
	InsertDocument(ctx context.Context, options InsertOptions) (WriteResult, error)
	UpdateDocuments(ctx context.Context, options UpdateOptions) (WriteResult, error)
	DeleteDocuments(ctx context.Context, options DeleteOptions) (WriteResult, error)
}

DocumentStore is the core-owned MongoDB contract for new consumers.

type Field added in v1.1.0

type Field struct {
	Name  string
	Value any
}

Field is a core-owned document field.

type Filter added in v1.1.0

type Filter map[string]any

Filter is a core-owned MongoDB filter document.

func FilterFromPairs added in v1.1.0

func FilterFromPairs(keyValue ...any) (Filter, error)

FilterFromPairs creates a core-owned MongoDB filter from key/value pairs.

func NewFilter added in v1.1.0

func NewFilter(fields ...Field) Filter

NewFilter creates a core-owned MongoDB filter document.

type FindOptions added in v1.1.0

type FindOptions struct {
	Collection string
	Filter     any
	Target     any
	Limit      int64
	Skip       int64
	Sort       any
}

FindOptions is the core-owned input for MongoDB read operations.

type InsertOptions added in v1.1.0

type InsertOptions struct {
	Collection string
	Document   any
}

InsertOptions is the core-owned input for MongoDB insert operations.

type MongoClient

type MongoClient struct {
	*mongo.Client
	// contains filtered or unexported fields
}

MongoClient client for mongo db

func Default deprecated

func Default() (*MongoClient, error)

Default return default client

Deprecated: use NewMongoClient or ClientStore.GetOrCreate with explicit config.

func Get deprecated

func Get() (*MongoClient, error)

Get return mongo client

Deprecated: use ClientStore.Get on an explicit store.

func NewMongoClient

func NewMongoClient(config *ConnectionConfig) (*MongoClient, error)

NewMongoClient return client from config

func (*MongoClient) Aggregate

func (m *MongoClient) Aggregate(
	ctx context.Context,
	collection string,
	value interface{},
	pipeline interface{},
	opts ...*options.AggregateOptions,
) ([]interface{}, error)

Aggregate aggregate rows

func (*MongoClient) BatchUpdateByID

func (m *MongoClient) BatchUpdateByID(ctx context.Context, collection string, data map[interface{}]interface{}) error

func (*MongoClient) Collection

func (m *MongoClient) Collection(name string, opts ...*options.CollectionOptions) *mongo.Collection

func (*MongoClient) Connection

func (m *MongoClient) Connection() *mongo.Client

func (*MongoClient) Count added in v1.1.0

func (m *MongoClient) Count(ctx context.Context, options CountOptions) (DocumentResult, error)

Count counts matching documents with core-owned options.

func (*MongoClient) CountDocuments

func (m *MongoClient) CountDocuments(
	ctx context.Context,
	collection string,
	filter interface{},
	opts ...*options.CountOptions,
) (int64, error)

CountDocuments count documents

func (*MongoClient) Database

func (m *MongoClient) Database(name string, opts ...*options.DatabaseOptions) *mongo.Database

func (*MongoClient) DeleteCollection

func (m *MongoClient) DeleteCollection(ctx context.Context, name string) error

func (*MongoClient) DeleteDocuments added in v1.1.0

func (m *MongoClient) DeleteDocuments(ctx context.Context, options DeleteOptions) (WriteResult, error)

DeleteDocuments deletes one or many documents with core-owned options.

func (*MongoClient) DeleteMany

func (m *MongoClient) DeleteMany(
	ctx context.Context,
	collection string,
	filter interface{},
	opts ...*options.DeleteOptions,
) error

DeleteMany delete all elements by condition

func (*MongoClient) DeleteOne

func (m *MongoClient) DeleteOne(
	ctx context.Context,
	collection string,
	filter interface{},
	opts ...*options.DeleteOptions,
) error

DeleteOne delete one element

func (*MongoClient) Drop

func (m *MongoClient) Drop(ctx context.Context, collection string) error

Drop collection

func (*MongoClient) Find

func (m *MongoClient) Find(
	ctx context.Context,
	collection string,
	value interface{},
	filter interface{},
	opts ...*options.FindOptions,
) ([]interface{}, error)

Find all and return

func (*MongoClient) FindDocuments added in v1.1.0

func (m *MongoClient) FindDocuments(ctx context.Context, options FindOptions) (DocumentResult, error)

FindDocuments reads documents with core-owned options.

func (*MongoClient) FindOne

func (m *MongoClient) FindOne(
	ctx context.Context,
	collection string,
	value interface{},
	filter interface{},
	opts ...*options.FindOneOptions,
) error

FindOne find and decode one element

func (*MongoClient) FindOneByID

func (m *MongoClient) FindOneByID(
	ctx context.Context,
	collection string,
	value interface{},
	id interface{},
	opts ...*options.FindOneOptions,
) error

FindOneByID return value by _id

func (*MongoClient) FindOneDocument added in v1.1.0

func (m *MongoClient) FindOneDocument(ctx context.Context, options FindOptions) (DocumentResult, error)

FindOneDocument reads one document with core-owned options.

func (*MongoClient) InsertDocument added in v1.1.0

func (m *MongoClient) InsertDocument(ctx context.Context, options InsertOptions) (WriteResult, error)

InsertDocument inserts one document with core-owned options.

func (*MongoClient) InsertMany

func (m *MongoClient) InsertMany(
	ctx context.Context,
	collection string,
	documents []interface{},
	opts ...*options.InsertManyOptions,
) error

InsertMany insert many documents

func (*MongoClient) InsertOne

func (m *MongoClient) InsertOne(
	ctx context.Context,
	collection string,
	value interface{},
	opts ...*options.InsertOneOptions,
) error

InsertOne insert single object

func (*MongoClient) UpdateByObject

func (m *MongoClient) UpdateByObject(
	ctx context.Context,
	collection string,
	value interface{},
	filter interface{},
	opts ...*options.UpdateOptions,
) error

UpdateByObject update to an object by filter

func (*MongoClient) UpdateDocuments added in v1.1.0

func (m *MongoClient) UpdateDocuments(ctx context.Context, options UpdateOptions) (WriteResult, error)

UpdateDocuments updates one or many documents with core-owned options.

func (*MongoClient) UpsertMany

func (m *MongoClient) UpsertMany(
	ctx context.Context,
	collection string,
	keys []interface{},
	documents []interface{},
) error

UpsertMany insert or update objects

func (*MongoClient) UpsertManyByFilter

func (m *MongoClient) UpsertManyByFilter(
	ctx context.Context,
	collection string,
	filterBy string,
	keys []interface{},
	documents []interface{},
) error

UpsertManyByFilter insert or update objects by filter

func (*MongoClient) UpsertOne

func (m *MongoClient) UpsertOne(
	ctx context.Context,
	collection string,
	update interface{},
	filter interface{},
	opts ...*options.UpdateOptions,
) error

UpsertOne insert or update single object

func (*MongoClient) WithDB

func (m *MongoClient) WithDB(name string) Client

type SortField added in v1.1.0

type SortField struct {
	Name       string
	Descending bool
}

SortField is a core-owned MongoDB sort field.

type UpdateOptions added in v1.1.0

type UpdateOptions struct {
	Collection string
	Filter     any
	Update     any
	Upsert     bool
	Many       bool
}

UpdateOptions is the core-owned input for MongoDB update operations.

type WriteResult added in v1.1.0

type WriteResult struct {
	InsertedCount int64
	MatchedCount  int64
	ModifiedCount int64
	DeletedCount  int64
	UpsertedCount int64
	InsertedID    any
	UpsertedID    any
}

WriteResult is the core-owned result for MongoDB write operations.

Directories

Path Synopsis
Package mock_mongodb is a generated GoMock package.
Package mock_mongodb is a generated GoMock package.

Jump to

Keyboard shortcuts

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