nosql

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2023 License: MIT Imports: 8 Imported by: 0

README

nosql

A wrapper to make it easier to use go.mongodb.org/mongo-driver

PkgGoDev

FindMany(...).Decode(...) chain

You can use the FindMany Decode chain to decode an array of documents from mongodb collection.

	collection := client.Database("test").Collection("test")

	var data []Elem
	if err := nosql.FindMany(ctx, collection, bson.D{}).Decode(&data); err != nil {
		return err
	}

	// Some using of documents slice
	for _, e := range data {
		fmt.Println(e.ID)
	}

It is like calling FindOne Decode chain to decode a single document in a standard mongodb driver.

FindMany wraps the func (*Collection) Find results, so the parameters are the same.

Data parameter of func Decode may be a pointer to an slice of struct. Also data parameter may be a pointer to an slice of pointers to a struct, see below.

If no documents are found, an empty slice is returned.

Minimal example

package main

import (
	"context"
	"fmt"

	"github.com/codeation/nosql"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Elem struct {
	Num int    `bson:"num"`
	Str string `bson:"str"`
}

func main() {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017/"))
	if err != nil {
		return
	}

	ctx := context.Background()
	if err = client.Connect(ctx); err != nil {
		return
	}
	defer client.Disconnect(ctx)

	collection := client.Database("test").Collection("test")

	var data []*Elem
	if err := nosql.FindMany(ctx, collection, bson.D{}).Decode(&data); err != nil {
		return
	}

	for _, e := range data {
		fmt.Println(e.Num, e.Str)
	}
}

Wrapper example

package main

import (
	"context"
	"fmt"

	"github.com/codeation/nosql"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Elem struct {
	Num int    `bson:"num"`
	Str string `bson:"str"`
}

func main() {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017/"))
	if err != nil {
		return
	}

	ctx := context.Background()
	if err = client.Connect(ctx); err != nil {
		return
	}
	defer client.Disconnect(ctx)

	db := nosql.NewDatabase(client.Database("test")) // wrap mongo.Database reference
	collection := db.Collection("test")

	var data []*Elem
	if err := collection.FindMany(ctx, bson.D{}).Decode(&data); err != nil {
		return
	}

	for _, e := range data {
		fmt.Println(e.Num, e.Str)
	}
}

AggregateMany(...).Decode(...) chain

You can use the AggregateMany Decode chain to decode an array of documents from aggregate command results.

	collection := client.Database("test").Collection("test")

	var data []Elem
	if err := nosql.AggregateMany(ctx, collection, bson.D{}).Decode(&data); err != nil {
		return err
	}

NextSequence func

NextSequence returns next ID value.

    id, err := db.NextSequence(ctx, "elemid")
    if err != nil {
        return err
    }
    e := &Element {
        ID: id,
        ... // Other fields
    }

This can be useful when you plan to use int64 values as IDs, or you need to know the new ID before inserting the document.

NextSequence uses the atomic operation $inc.

Make sure that the "counters" collection has an index by "id" field:

db.counters.createIndex( { id: 1 } )

Documentation

Overview

Package nosql implements wrappers for go.mongodb.org/mongo-driver

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Aggregater added in v1.2.1

type Aggregater interface {
	Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*mongo.Cursor, error)
}

Aggregater is a part of the mongo.Collection interface.

type Collection

type Collection struct {
	*mongo.Collection
}

Collection is a mongo.Collection wrapper.

func (*Collection) AggregateMany added in v1.2.0

func (c *Collection) AggregateMany(
	ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions,
) *ManyResult

AggregateMany returns aggregate command results.

func (*Collection) FindMany

func (c *Collection) FindMany(
	ctx context.Context, filter interface{}, opts ...*options.FindOptions,
) *ManyResult

FindMany finds all documents that match the filter and options.

type Database

type Database struct {
	*mongo.Database
}

Database is a mongo.Database wrapper.

func NewDatabase

func NewDatabase(db *mongo.Database) *Database

NewDatabase creates a new Database instance.

func (*Database) Collection

func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection

Collection returns a handle for collection of database.

func (*Database) InitSequence

func (db *Database) InitSequence(ctx context.Context, idName string, idValue int64) error

InitSequence sets last used value for ID name; InitSequence needs for data migration only.

func (*Database) NextSequence

func (db *Database) NextSequence(ctx context.Context, idName string) (int64, error)

NextSequence returns next ID value. Make sure that the "counters" collection has an index by "id" field.

func (*Database) NextSequences

func (db *Database) NextSequences(ctx context.Context, idName string, size int64) (int64, error)

NextSequences returns first ID value for specified range size.

type Databases

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

Databases represents mongodb database pool.

func Open

func Open(ini IniFile, opts ...*options.ClientOptions) *Databases

Open returns mongodb database pool.

func (*Databases) Close

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

Close closes mongo database pool.

func (*Databases) Get

func (d *Databases) Get(ctx context.Context, name string, dbOpts ...*options.DatabaseOptions,
) (*Database, error)

Get returns database hanle.

type Finder added in v1.1.0

type Finder interface {
	Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error)
}

Finder is a part of the mongo.Collection interface.

type IniFile

type IniFile interface {
	Get(section string, name string) string
}

IniFile is interface to read INI file variables.

type ManyResult

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

ManyResult contains Find results.

func AggregateMany added in v1.2.1

func AggregateMany(
	ctx context.Context, aggregater Aggregater, pipeline interface{}, opts ...*options.AggregateOptions,
) *ManyResult

AggregateMany executes an aggregate command against the collection. Any reference to mongo.Collection conforms to Aggregater interface.

func FindMany added in v1.1.0

func FindMany(
	ctx context.Context, finder Finder, filter interface{}, opts ...*options.FindOptions,
) *ManyResult

FindMany finds all documents from the collection that match the filter and options. Any reference to mongo.Collection conforms to Finder interface.

func (*ManyResult) Cursor

func (a *ManyResult) Cursor() *mongo.Cursor

Cursor returns a underlying *mongo.Cursor.

func (*ManyResult) Decode

func (a *ManyResult) Decode(data interface{}) error

Decode decodes all found documents into a variable. The data parameter may be a pointer to an slice of struct. Also data parameter may be a pointer to an slice of pointers to a struct. For examples:

var data1 []Struct // slice of struct
err := collection.FindMany(ctx, bson.D{}).Decode(&data1) // pointer to an slice of ...

var data2 []*Struct // slice of pointers to a struct
err := collection.FindMany(ctx, bson.D{}).Decode(&data2) // pointer to an slice of ...

If no documents are found, an empty slice is returned.

func (*ManyResult) Err

func (a *ManyResult) Err() error

Err returns a underlying error.

Jump to

Keyboard shortcuts

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