mongodb

package module
v0.34.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: Apache-2.0 Imports: 17 Imported by: 4

README

🍃 data-mongo

Go Reference Version Build Status Go Report Card Codecov

MongoDB Adapter for the "data" Interface

data-mongo implements the benpate/data interfaces (Server, Session, Collection, Iterator) on top of the official MongoDB Go driver. It lets application code perform CRUD operations against MongoDB through the generic data abstraction, without importing the driver directly. Queries are written as benpate/exp expressions, which this package translates into native BSON.

server, err := mongodb.New("mongodb://localhost:27017", "mydatabase", nil)
session, err := server.Session(ctx)
collection := session.Collection("users")

err = collection.Load(exp.Equal("username", "sarah"), &user)

Pull Requests Welcome

I'm trying to make data-mongo the best it can be, and your help is greatly appreciated. If you find a bug or have an idea for a new feature, please open an issue or submit a pull request. We're all in this together! 🍃

Documentation

Overview

Package mongodb implements the benpate/data interfaces (Server, Session, Collection, Iterator) on top of the official MongoDB Go driver, so that application code can run CRUD operations against MongoDB without importing the driver directly.

Queries are written as benpate/exp expressions, which this package translates into native BSON:

server, err := mongodb.New("mongodb://localhost:27017", "mydatabase", nil)
session, err := server.Session(ctx)
collection := session.Collection("users")

err = collection.Load(exp.Equal("username", "sarah"), &user)

String matching is escaped, and type mismatches fail closed

The BEGINS, CONTAINS, and ENDS operators compile to a MongoDB $regex, so the comparison value is escaped with regexp.QuoteMeta before it is embedded. An untrusted value therefore matches as a literal: it can neither change the meaning of the pattern nor inject a pathological one (ReDoS).

A value of the wrong Go type -- a number given to CONTAINS, a string given to EXISTS -- produces an empty comparison, which MongoDB matches against no records at all. Malformed input narrows a query; it never widens one.

The guarantee covers the comparison VALUE, not the field name. A caller who builds an expression from an unvalidated field name is passing that name straight through to MongoDB.

Delete is virtual; HardDelete is physical

Collection.Delete marks an object deleted and re-saves it, leaving the record in the database. Only HardDelete issues a real DeleteMany.

Iterator.Count reports one batch

A cursor only knows what the server has already sent it, so Iterator.Count returns the records remaining in the CURRENT batch rather than the size of the whole result set. This is a deliberate deviation from the data.Iterator interface, which specifies the total; reporting the total here would mean an extra round trip on every call. Use Collection.Count for a true total.

Iterator.Error reports the first failure encountered while iterating, including a record that would not decode into the caller's target. Always check it after the loop -- a decode failure ends iteration early, and without this check a short read is indistinguishable from a complete one.

Sessions, contexts, and transactions

The query context is carried on the Session and Collection structs, set when the session is opened. This is a deliberate deviation from "don't store a context in a struct," dictated by the shape of the data interfaces, whose methods take no ctx argument.

Session.Close is a no-op. Connections belong to the long-lived *mongo.Client pool, not the session, so per-request cleanup happens by cancelling the context passed to Server.Session.

Server.WithTransaction uses majority read/write concern and causal consistency, and therefore requires a replica set or mongos; it fails against a standalone mongod.

Slow-query logging

Slow-query logging is off by default and global. SetLogTimeout enables it for the whole process, and is safe to call while queries are in flight.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExpressionToBSON

func ExpressionToBSON(criteria exp.Expression) bson.M

ExpressionToBSON converts an exp.Expression into a pure bson query filter.

func SetLogTimeout added in v0.30.2

func SetLogTimeout(timeout int)

SetLogTimeout configures the threshold (in milliseconds) above which slow queries are logged. A value of zero or less disables slow-query logging.

Types

type Collection

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

Collection wraps a mongodb.Collection with all of the methods required by the data.Collection interface

func NewCollection added in v0.28.3

func NewCollection(collection *mongo.Collection) Collection

NewCollection creates a new Collection object directly from a mongo.Collection

func (Collection) Context added in v0.30.4

func (c Collection) Context() context.Context

Context returns the context associated with this collection.

func (Collection) Count added in v0.28.0

func (c Collection) Count(criteria exp.Expression, options ...option.Option) (int64, error)

Count returns the number of records in the collection that match the provided criteria.

func (Collection) Delete

func (c Collection) Delete(object data.Object, note string) error

Delete removes a single object from the database, using a "virtual delete"

func (Collection) HardDelete added in v0.1.0

func (c Collection) HardDelete(criteria exp.Expression) error

HardDelete physically removes an object from the database.

func (Collection) Iterator added in v0.28.0

func (c Collection) Iterator(criteria exp.Expression, options ...option.Option) (data.Iterator, error)

Iterator retrieves a group of objects from the database as an iterator

func (Collection) Load

func (c Collection) Load(criteria exp.Expression, target data.Object, options ...option.Option) error

Load retrieves a single object from the database

func (Collection) Mongo

func (c Collection) Mongo() *mongo.Collection

Mongo returns the underlying mongodb collection for libraries that need to bypass this abstraction.

func (Collection) Query added in v0.2.2

func (c Collection) Query(target any, criteria exp.Expression, options ...option.Option) error

Query retrieves a group of objects from the database and populates a target interface

func (Collection) Save

func (c Collection) Save(object data.Object, note string) error

Save inserts/updates a single object in the database.

type Iterator

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

Iterator wraps the mongodb Cursor object

func NewIterator

func NewIterator(ctx context.Context, cursor *mongo.Cursor) *Iterator

NewIterator returns a fully populated Iterator object

func (*Iterator) Close

func (iterator *Iterator) Close() error

Close closes the wrapped Cursor. A cursor-less iterator has nothing to close.

func (*Iterator) Count

func (iterator *Iterator) Count() int

Count returns the number of records remaining in the cursor's CURRENT batch, which is the most the driver can report without another round trip to the server. For a result set larger than one batch this is less than the total.

func (*Iterator) Error added in v0.21.0

func (iterator *Iterator) Error() error

Error returns the first error encountered while iterating, whether it came from decoding a record or from the wrapped Cursor itself.

func (*Iterator) Next

func (iterator *Iterator) Next(output any) bool

Next populates the next value from the wrapped Cursor, or returns FALSE. A cursor-less iterator is always exhausted.

type Server

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

Server is an abstract representation of a MongoDB database. It implements the data.Server interface, so that it should be usable anywhere that requires a data.Server.

func New

func New(uri string, database string, opt *options.ClientOptions) (Server, error)

New returns a fully populated mongodb.Server. It requires that you provide the URI for the mongodb cluster, along with the name of the database to be used for all transactions.

func NewServer added in v0.30.4

func NewServer(database *mongo.Database) Server

NewServer wraps an existing *mongo.Database in a data.Server.

func (Server) Client added in v0.30.4

func (server Server) Client() *mongo.Client

Client returns the underlying mongodb client for libraries that need to bypass this abstraction.

func (Server) Database added in v0.30.4

func (server Server) Database() *mongo.Database

Database returns the underlying mongodb database for libraries that need to bypass this abstraction.

func (Server) Session

func (server Server) Session(ctx context.Context) (data.Session, error)

Session returns a new client session that can be used to perform CRUD transactions on this datastore.

func (Server) WithTransaction added in v0.30.4

func (server Server) WithTransaction(ctx context.Context, fn data.TransactionCallbackFunc) (any, error)

WithTransaction runs fn inside a MongoDB transaction, committing if it returns nil and rolling back if it returns an error. Transactions require the server to be a replica set or mongos.

type Session

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

Session represents a single database session, such as a session encompassing all of the database queries to respond to a single REST service call.

func NewSession added in v0.28.3

func NewSession(database *mongo.Database) Session

NewSession generates a new Session object from a mongo.Database

func (Session) Close

func (s Session) Close()

Close is a no-op that exists to satisfy the data.Session interface. This Session holds no per-session resources: connections are owned by the long-lived *mongo.Client pool and recycled automatically after each operation. Callers release per-request resources by cancelling the context they passed to Server.Session, not by calling Close.

func (Session) Collection

func (s Session) Collection(collection string) data.Collection

Collection returns a reference to an individual database collection.

func (Session) Context added in v0.30.4

func (s Session) Context() context.Context

Context returns the context associated with this session.

func (Session) Mongo

func (s Session) Mongo() *mongo.Database

Mongo returns the underlying mongodb database for libraries that need to bypass this abstraction.

Jump to

Keyboard shortcuts

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