mongodb

package
v0.2.8 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FindPageOptionSyncPool = sync.Pool{
	New: func() interface{} {

		return new(FindPageOption)
	},
}

FindPageOptionSyncPool is a sync.Pool that stores FindPageOption objects. sync.Pool is a type-safe, reusable object pool provided by Go's standard library.

Functions

func IsNoResult

func IsNoResult(err error) bool

func MustHexToObjectId

func MustHexToObjectId(strId string) primitive.ObjectID

Types

type DefaultModel

type DefaultModel struct {
	Id             primitive.ObjectID `bson:"_id" json:"id"`                            // The document's ID.
	CreateTime     int64              `bson:"create_time" json:"create_time"`           // The document's creation time.
	LastModifyTime int64              `bson:"last_modify_time" json:"last_modify_time"` // The document's modification time.
}

DefaultModel is a struct that represents a default model for MongoDB documents. It includes fields for the document's ID, creation time, and modification time.

func (*DefaultModel) BeforeInsert

func (m *DefaultModel) BeforeInsert(ctx context.Context) error

BeforeInsert is a method that is called before a document is inserted into the database. It sets the document's ID and timestamps to their default values.

func (*DefaultModel) BeforeUpdate

func (m *DefaultModel) BeforeUpdate(ctx context.Context) error

BeforeUpdate is a method that is called before a document is updated in the database. It sets the document's modification time to the current time.

func (*DefaultModel) ColName

func (m *DefaultModel) ColName() string

ColName returns the name of the collection to which the DefaultModel belongs. Currently, this method returns a placeholder string.

func (*DefaultModel) GetId

func (m *DefaultModel) GetId() string

GetId returns the hexadecimal string representation of the Id field of the DefaultModel. It uses the Hex() method from the Id field to convert the Id to its string representation.

func (*DefaultModel) GetObjectID

func (m *DefaultModel) GetObjectID() primitive.ObjectID

GetObjectID returns the ObjectID of the DefaultModel.

func (*DefaultModel) PutId

func (m *DefaultModel) PutId(id string)

PutId sets the Id field of the DefaultModel using a hexadecimal string.

type FindPageOption

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

FindPageOption is a struct that holds the fields and selector for a page.

func NewFindPageOption

func NewFindPageOption() *FindPageOption

NewFindPageOption is a function that creates a new FindPageOption. It does this by acquiring a FindPageOption from the pool.

func (*FindPageOption) SetSelectField

func (o *FindPageOption) SetSelectField(bson interface{}) *FindPageOption

SetSelectField is a method on FindPageOption that sets the selector. It takes an interface as a parameter, allowing any type to be passed. It returns a pointer to the FindPageOption for method chaining.

func (*FindPageOption) SetSortField

func (o *FindPageOption) SetSortField(field ...string) *FindPageOption

SetSortField is a method on FindPageOption that sets the fields to sort by. It takes a variadic parameter of strings, allowing multiple fields to be passed. It returns a pointer to the FindPageOption for method chaining.

type IDefaultModel

type IDefaultModel interface {
	ColName() string                 // Returns the name of the MongoDB collection associated with the model.
	GetId() string                   // Returns the string representation of the model's ID.
	GetObjectID() primitive.ObjectID // Returns the ObjectID of the model.
	PutId(id string)                 // Sets the model's ID using a string.
	// contains filtered or unexported methods
}

IDefaultModel is an interface that defines the methods required for a default model. The interface includes methods to retrieve and manipulate the ID, as well as the creation and modification times of the model. Additionally, it provides a method to obtain the MongoDB collection name associated with the model.

type Logger

type Logger interface {
	Debug(args ...any)
	Info(args ...any)
	Warn(args ...any)
	Error(args ...any)
	Panic(args ...any)

	Debugf(format string, args ...any)
	Infof(format string, args ...any)
	Warnf(format string, args ...any)
	Errorf(format string, args ...any)
	Panicf(format string, args ...any)
}

type MongoDB

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

func NewMongoDB

func NewMongoDB(connectionUri string, databaseName string, logger ...Logger) (*MongoDB, error)

NewMongoDB returns a new instance of MongoDB connected to the specified database. It takes a connection URI, database name, and an optional logger as parameters. If no logger is provided, it uses a default logger. It returns a pointer to MongoDB and an error if there is any.

func (*MongoDB) Aggregate

func (m *MongoDB) Aggregate(model IDefaultModel, pipeline any, res any) error

Aggregate is a method that performs an aggregation pipeline operation on a MongoDB collection.

func (*MongoDB) Close

func (m *MongoDB) Close() error

Close closes the connection to the database.

func (*MongoDB) Count added in v0.2.7

func (m *MongoDB) Count(model IDefaultModel, filter any) (int64, error)

Count is a method that returns the total number of documents in a MongoDB collection based on the provided filter.

func (*MongoDB) Delete

func (m *MongoDB) Delete(model IDefaultModel) error

Delete is a method that deletes a single document from a MongoDB collection.

func (*MongoDB) DeleteMany added in v0.2.0

func (m *MongoDB) DeleteMany(model IDefaultModel, filter any) (*omgo.DeleteResult, error)

DeleteMany is a method that deletes multiple documents from a MongoDB collection based on the provided filter.

func (*MongoDB) Find

func (m *MongoDB) Find(model IDefaultModel, filter any) omgo.QueryI

Find retrieves documents from a MongoDB collection based on the provided filter and model. It returns an omgo.QueryI interface that can be used to further specify the query. If the MongoDB instance is not initialized, it logs an error and returns nil. If the filter is nil, it uses an empty filter (bson.D{}) by default. The returned query can be used to add projections, limits, sorting, and other query modifiers. Example usage:

query := mongo.Find(model, bson.M{"name": "John"})
query.Select(bson.M{"age": 1})
query.Sort(bson.M{"age": -1})
query.Skip(5)
query.Limit(10)
cursor := query.Cursor()
for cursor.Next(context.Background()) {
  var result *MyModel
  cursor.Decode(&result)
  // process the result
}

func (*MongoDB) FindById

func (m *MongoDB) FindById(model IDefaultModel, id string, res any) (bool, error)

FindById is a method that finds a single document in a MongoDB collection based on the provided id.

func (*MongoDB) FindOne

func (m *MongoDB) FindOne(model IDefaultModel, filter any, res any) (bool, error)

FindOne is a method that finds a single document in a MongoDB collection based on the provided filter.

func (*MongoDB) FindPage

func (m *MongoDB) FindPage(model IDefaultModel, filter any, res any, pageSize int64, currentPage int64, option ...*FindPageOption) (totalDoc int64, totalPage int64)

FindPage is a method that finds a page of documents in a MongoDB collection based on the provided filter. It returns the total number of documents and the total number of pages.

func (*MongoDB) FindWithCursor

func (m *MongoDB) FindWithCursor(model IDefaultModel, filter any) omgo.CursorI

FindWithCursor is a method that returns an omgo.CursorI interface based on the provided model and filter. If the MongoDB instance is not initialized, it logs an error and returns nil. If the filter is nil, it uses an empty filter (bson.D{}) by default. It returns the cursor object.

func (*MongoDB) Insert

func (m *MongoDB) Insert(model IDefaultModel) (*omgo.InsertOneResult, error)

Insert is a method that inserts a single document into a MongoDB collection.

func (*MongoDB) InsertMany

func (m *MongoDB) InsertMany(model IDefaultModel, docs []any) (*omgo.InsertManyResult, error)

InsertMany inserts multiple documents into a MongoDB collection based on the provided model and slice of documents. It returns the result of the insert operation and an error if any. If the MongoDB instance is not initialized, it logs an error and returns nil. Example usage:

model := MyModel{}
docs := []MyModel{
	{Name: "Jane", Age: 25},
	{Name: "Doe", Age: 35},
}
result, err := mongo.InsertMany(&model, docs)
if err != nil {
	// handle error
}
fmt.Println(result.InsertedIDs)

Parameter model: The model or collection name. Parameter docs: The slice of documents to be inserted. Returns: *omgo.InsertManyResult, error

func (*MongoDB) IsExist added in v0.2.7

func (m *MongoDB) IsExist(model IDefaultModel, filter any) (bool, error)

IsExist is a method that checks if a document exists in a MongoDB collection based on the provided filter.

func (*MongoDB) Ping

func (m *MongoDB) Ping() error

Ping checks the connection to the database.

func (*MongoDB) Update

func (m *MongoDB) Update(model IDefaultModel) error

Update is a method that updates a single document in a MongoDB collection.

func (*MongoDB) UseUpdater

func (m *MongoDB) UseUpdater(model IDefaultModel) *updater

Jump to

Keyboard shortcuts

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