mongodb

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindTyped added in v1.3.0

func FindTyped[T any](c *Client, ctx context.Context, tableName string, filter interface{}) ([]T, error)

FindTyped 按过滤条件查询并直接解码为 []T,类型安全。 filter 为 nil 时查询全部文档。

Types

type Client

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

Client 封装 MongoDB 客户端与默认数据库配置。

func GetClient

func GetClient(dbCig *MongoDBConfig, ctx context.Context) (*Client, error)

GetClient 创建 MongoDB 客户端;配置或 Context 为空时返回明确错误。 调用方应使用带超时的 Context,并在使用完成后调用 Disconnect。

func (*Client) Aggregate

func (c *Client) Aggregate(ctx context.Context, tableName string, groupStage mongo.Pipeline) ([]bson.M, error)

Aggregate 执行聚合管道并返回全部结果,游标统一关闭并处理关闭错误。

func (*Client) DeleteOne

func (c *Client) DeleteOne(ctx context.Context, tableName string, filter interface{}) error

DeleteOne 删除单条匹配文档。

func (*Client) Disconnect

func (c *Client) Disconnect(ctx context.Context) error

Disconnect 关闭 MongoDB 客户端连接;重复调用安全。

func (*Client) Find

func (c *Client) Find(ctx context.Context, tableName string, filters ...interface{}) ([]bson.M, error)

Find 按过滤条件查询文档集合;游标统一关闭并处理解码与遍历错误。 新代码建议使用类型安全的 FindTyped。

func (*Client) FindOne

func (c *Client) FindOne(ctx context.Context, tableName string, filter interface{}) *mongo.SingleResult

FindOne 查询单条文档。

func (*Client) InsertOne

func (c *Client) InsertOne(ctx context.Context, tableName string, document interface{}) (interface{}, error)

InsertOne 插入单条文档并返回插入 ID。

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping 检查 MongoDB 主节点连通性。

func (*Client) UpdateOne

func (c *Client) UpdateOne(ctx context.Context, tableName string, filter, update interface{}) (*mongo.UpdateResult, error)

UpdateOne 更新单条匹配文档。

type MongoDBConfig

type MongoDBConfig struct {
	Timeout  time.Duration `mapstructure:"timeout" json:"timeout" yaml:"timeout"` // 超时秒数
	DB       string        `mapstructure:"db" json:"db" yaml:"db"`
	Addr     string        `mapstructure:"addr" json:"addr" yaml:"addr"` // host:port
	User     string        `mapstructure:"user" json:"user" yaml:"user"` // 可选用户名
	Password string        `mapstructure:"password" json:"password" yaml:"password"`
}

MongoDBConfig 定义 MongoDB 连接配置。 Password 为敏感字段,禁止写入日志或错误信息。

func (*MongoDBConfig) GetApplyURI

func (md *MongoDBConfig) GetApplyURI() string

GetApplyURI 构造 MongoDB 连接串。 提供用户名时使用 URL 编码的凭据;返回的 URI 禁止写入日志。

Jump to

Keyboard shortcuts

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