mgo

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: GPL-3.0 Imports: 10 Imported by: 1

README

github.com/maczh/mgo SDK包

English Version

仿gopkg.in/mgo.v2驱动包,基于mongodb官方go语言驱动包。

一、概览

由于gopkg.in/mgo.v2包长期未更新,对mongodb的版本仅支持到4.4.x版本,但是mgo.v2封装得非常好用,比官方包要易用,因此仿照mgo.v2的主要常用功能利用官方包封装出一个仿mgo包,可以支持最新版本的mongodb。

使用范例:

package main

import (
	"go.mongodb.org/mongo-driver/bson"
    "github.com/maczh/mgo"
    "fmt"
)

type user struct {
	Name string `bson:"name"`
	Age  int    `bson:"age"`
}

func main() {
	uri := "mongodb://user:password@localhost:27017/testdb?retryWrites=true&serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=test&authMechanism=SCRAM-SHA-256"
	//创建mongodb连接
    client, err := mgo.Dial(uri)
	if err != nil {
		t.Log(err)
		return
	}
	var docs = []any{
		user{Name: "user7", Age: 18},
		user{Name: "user8", Age: 23},
		user{Name: "user9", Age: 26},
	}
    //批量插入数据
	err = client.DB("testdb").C("users").Insert(docs...)
	if err != nil {
		fmt.Println(err)
		return
	}
    //当url串中包含database名时,DB("")直接使用url串中的数据库
	db := client.DB("").C("users")
	var result []user
    //查询数据,带分页
	query := db.Find(map[string]any{"age": bson.M{"$gte": 25}})
	err = query.Skip(1).Limit(2).Sort("age").All(&result)
	if err != nil {
		fmt.Println(err)
		return
	}
	t.Log(result)
    //按之前的查询语句获取总记录数
	count, err := query.CountAll()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("总记录数:%d\n", count)
}

二、SDK详细介绍

2.1 公共函数
func Dial()函数
func Dial(url string) (*Session, error)

根据mongodb的url连接串建立数据库连接,其中url串格式:

mongodb://[user:pass@]host1[:port1][,host2[:port2],...][/database][?options]

options选项说明:

  connect=direct

       Disables the automatic replica set server discovery logic, and
       forces the use of servers provided only (even if secondaries).
       Note that to talk to a secondary the consistency requirements
       must be relaxed to Monotonic or Eventual via SetMode.

   connect=replicaSet

	   Discover replica sets automatically. Default connection behavior.

   replicaSet=<setname>

       If specified will prevent the obtained session from communicating
       with any server which is not part of a replica set with the given name.
       The default is to communicate with any server specified or discovered
       via the servers contacted.

   authSource=<db>

       Informs the database used to establish credentials and privileges
       with a MongoDB server. Defaults to the database name provided via
       the URL path, and "admin" if that's unset.

   authMechanism=<mechanism>

      Defines the protocol for credential negotiation. Defaults to "MONGODB-CR",
      which is the default username/password challenge-response mechanism.

   gssapiServiceName=<name>

      Defines the service name to use when authenticating with the GSSAPI
      mechanism. Defaults to "mongodb".

   maxPoolSize=<limit>

      Defines the per-server socket pool limit. Defaults to 10.

1.单机库连接串: mongodb://user:password@localhost:27017/testdb?retryWrites=true&serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=test&authMechanism=SCRAM-SHA-256

2.集群库连接串: mongodb://user:password@server1:27017,server2:27017/testdb?retryWrites=true&serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=test&authMechanism=SCRAM-SHA-256&replicaSet=repSet1

func DialWithTimeout()函数
func DialWithTimeout(url string, timeout time.Duration, poolMax int) (*Session, error)

带参数连接MongoDB数据库,参数:

参数名 参数说明
url MongoDB连接串
timeout 连接超时,最小超时10秒
poolMax 连接池最大值,默认最小值为10
func ToAnySlice()函数
func ToAnySlice(docs any) []any

将结构对象数组转换成[]any函数

2.2 Session类

数据库连接会话类

func (s *Session) Clone()函数
func (s *Session) Clone() *Session

克隆一个MongoDB连接。

func (s *Session) Copy() 函数
func (s *Session) Copy() *Session

复制一个MongoDB连接,复制的连接是新建的连接。

func (s *Session) DB()函数
func (s *Session) DB(name string) *Database

选择连接的指定库名为name的数据库,返回*Database对象,相当于use命令。

若name参数为空字符串,则选择连接串中自带的数据库。

func (s *Session) Close()函数
func (s *Session) Close()

关闭连接

func (s *Session) Ping()函数
func (s *Session) Ping() error

检测数据库连接是否正常

func (s *Session) DatabaseNames()函数
func (s *Session) DatabaseNames() (names []string, err error)

获取MongoDB中所有的数据库名称,相当于show dbs命令

2.3 Database类

数据库类,用于针对指定库名称的数据库的操作

func (d *Database) C(name string)函数
func (d *Database) C(name string) *Collection

指定Collection表名称,获得表对象*Collection,若指定表尚未创建,则在插入第一条记录时自动创建

func (d *Database) Session()函数
func (d *Database) Session() *Session

获取当前Database对象对应的连接会话对象

func (db *Database) CollectionNames()函数
func (db *Database) CollectionNames() (names []string, err error)

获取当前数据库中所有的collection表名称

func (d *Database) AddUser() 函数
func (d *Database) AddUser(username, password string, readOnly bool) error

添加数据库的用户,当前连接用户必须要有当前库的管理权限。新增的用户对本库只有只读和读写两种权限

参数 参数说明
username 用户名
password 登录密码
readOnly 是否只读,true-只读,false-读写
func (d *Database) RemoveUser()函数
func (d *Database) RemoveUser(username string) error

删除数据库的用户

func (d *Database) DropDatabase()函数
func (d *Database) DropDatabase() error

删除当前数据库

2.4 Collection类

collection表对象,针对当前表的所有操作

func (c *Collection) Database()函数
func (c *Collection) Database() *Database

获取当前表对应的数据库对象

func (c *Collection) DropCollection()函数
func (c *Collection) DropCollection() error

删除当前表

func (c *Collection) Insert()函数
func (c *Collection) Insert(docs ...any) error

插入数据,插入一条记录,也可以批量插入多条数据

func (c *Collection) Update()函数
func (c *Collection) Update(selector, update interface{}) error

更新一条记录

参数 参数说明
selector 查询条件
update 更新的字段
func (c *Collection) Find()函数
func (c *Collection) Find(query interface{}) *Query

查询语句返回*Query对象

func (c *Collection) UpdateAll() 函数
func (c *Collection) UpdateAll(selector interface{}, update interface{}) (*ChangeInfo, error)

批量更新记录

func (c *Collection) UpdateId()函数
func (c *Collection) UpdateId(id, update interface{}) error

通过id更新记录

func (c *Collection) Upsert()函数
func (c *Collection) Upsert(selector, update interface{}) (*mongo.UpdateResult, error)

插入或更新函数

func (c *Collection) UpsertId()函数
func (c *Collection) UpsertId(id, update interface{}) (*mongo.UpdateResult, error)

按ID插入或更新

func (c *Collection) Remove() 函数
func (c *Collection) Remove(selector interface{}) error

按条件删除符合条件的第一条记录

func (c *Collection) RemoveId()函数
func (c *Collection) RemoveId(id interface{}) error

按ID删除记录

func (c *Collection) RemoveAll()函数
func (c *Collection) RemoveAll(selector interface{}) (*mongo.DeleteResult, error)

删除符合条件的所有记录

func (c *Collection) Count()函数
func (c *Collection) Count() (int, error)

统计表的总记录数

func (c *Collection) EnsureIndex() 函数
func (c *Collection) EnsureIndex(index Index) error

创建索引

2.5 Query类

专用于查询处理的链式处理

func (q *Query) Collection()函数
func (q *Query) Collection() *Collection

返回上级表对象

func (q *Query) Select()函数
func (q *Query) Select(selector interface{}) *Query

选择返回的字段

func (q *Query) Skip()函数
func (q *Query) Skip(n int) *Query

跳过记录数,用于分页

func (q *Query) Limit()函数
func (q *Query) Limit(n int) *Query

返回最大记录数,用于分页

func (q *Query) Sort()函数
func (q *Query) Sort(fields ...string) *Query

按指定字段排序,排序优先于Skip和Limit

func (q *Query) One()函数
func (q *Query) One(result interface{}) error

查询返回第一条记录

func (q *Query) All()函数
func (q *Query) All(result interface{}) error

返回符合条件的所有记录,包括分页控制条件

func (q *Query) Count()函数
func (q *Query) Count() (int, error)

统计符合条件的记录数,包括Skip和Limit控制

func (q *Query) CountAll()函数
func (q *Query) CountAll() (int, error)

统计符合条件的总记录数,Skip和Limit不生效

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound 模拟mgo.v2的ErrNotFound

Functions

func ToAnySlice added in v1.0.1

func ToAnySlice(docs any) []any

ToAnySlice 将对象数组转换成可直接插入的[]any切片

Types

type ChangeInfo

type ChangeInfo struct {
	// Updated reports the number of existing documents modified.
	// Due to server limitations, this reports the same value as the Matched field when
	// talking to MongoDB <= 2.4 and on Upsert and Apply (findAndModify) operations.
	Updated    int
	Removed    int         // Number of documents removed
	Matched    int         // Number of documents matched but not necessarily changed
	UpsertedId interface{} // Upserted _id field, when not explicitly provided
}

type Collection

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

Collection 模拟mgo.v2的Collection

func (*Collection) Count

func (c *Collection) Count() (int, error)

Count 模拟mgo.v2的Count方法

func (*Collection) Database added in v1.0.3

func (c *Collection) Database() *Database

Database 获取Collection所属的Database

func (*Collection) DropCollection

func (c *Collection) DropCollection() error

DropCollection 模拟mgo.v2的DropCollection方法

func (*Collection) EnsureIndex

func (c *Collection) EnsureIndex(index Index) error

EnsureIndex 模拟mgo.v2的EnsureIndex方法

func (*Collection) Find

func (c *Collection) Find(query interface{}) *Query

Find 模拟mgo.v2的Find方法

func (*Collection) Insert

func (c *Collection) Insert(docs ...any) error

Insert 模拟mgo.v2的Insert方法

func (*Collection) Remove

func (c *Collection) Remove(selector interface{}) error

Remove 模拟mgo.v2的Remove方法

func (*Collection) RemoveAll

func (c *Collection) RemoveAll(selector interface{}) (*mongo.DeleteResult, error)

RemoveAll 模拟mgo.v2的RemoveAll方法

func (*Collection) RemoveId

func (c *Collection) RemoveId(id interface{}) error

RemoveId 模拟mgo.v2的RemoveId方法

func (*Collection) ReplaceOne added in v1.0.4

func (c *Collection) ReplaceOne(selector, updatedDoc interface{}) error

func (*Collection) Update

func (c *Collection) Update(selector, update interface{}) error

Update 模拟mgo.v2的Update方法

func (*Collection) UpdateAll

func (c *Collection) UpdateAll(selector interface{}, update interface{}) (*ChangeInfo, error)

UpdateAll 模拟mgo.v2的UpdateAll方法

func (*Collection) UpdateId

func (c *Collection) UpdateId(id, update interface{}) error

UpdateId 模拟mgo.v2的UpdateId方法

func (*Collection) Upsert

func (c *Collection) Upsert(selector, update interface{}) (*mongo.UpdateResult, error)

Upsert 模拟mgo.v2的Upsert方法

func (*Collection) UpsertId

func (c *Collection) UpsertId(id, update interface{}) (*mongo.UpdateResult, error)

UpsertId 模拟mgo.v2的UpsertId方法

type Database

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

Database 模拟mgo.v2的Database

func (*Database) AddUser

func (d *Database) AddUser(username, password string, readOnly bool) error

AddUser 模拟mgo.v2的AddUser方法

func (*Database) C

func (d *Database) C(name string) *Collection

C 模拟mgo.v2的C方法

func (*Database) CollectionNames

func (db *Database) CollectionNames() (names []string, err error)

CollectionNames 模拟mgo.v2的CollectionNames方法

func (*Database) DropDatabase

func (d *Database) DropDatabase() error

DropDatabase 模拟mgo.v2的DropDatabase方法

func (*Database) RemoveUser

func (d *Database) RemoveUser(username string) error

RemoveUser 模拟mgo.v2的RemoveUser方法

func (*Database) Run

func (d *Database) Run(cmd interface{}, result interface{}) error

Run 模拟mgo.v2的Run方法

func (*Database) Session added in v1.0.3

func (d *Database) Session() *Session

Session 获取Database所属的Session

type Index

type Index struct {
	Keys               []string
	Unique             bool
	Background         bool
	Sparse             bool
	ExpireAfterSeconds int
	Name               string
}

Index 模拟mgo.v2的Index

type Iter

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

Iter 模拟mgo.v2的Iter

func (*Iter) Close

func (i *Iter) Close() error

Close 模拟mgo.v2的Close方法

func (*Iter) Err

func (i *Iter) Err() error

Err 模拟mgo.v2的Err方法

func (*Iter) Next

func (i *Iter) Next(result interface{}) bool

Next 模拟mgo.v2的Next方法

type Mode

type Mode int

Mode 模拟mgo.v2的查询模式

const (
	// 各种Mode常量定义
	Monotonic Mode = iota
	Eventual
	Strong
)

type Query

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

Query 模拟mgo.v2的Query

func (*Query) All

func (q *Query) All(result interface{}) error

All 模拟mgo.v2的All方法

func (*Query) Collection added in v1.0.3

func (q *Query) Collection() *Collection

Collection 获取Query所属的Collection

func (*Query) Count

func (q *Query) Count() (int, error)

Count 模拟mgo.v2的Count方法

func (*Query) CountAll added in v1.0.2

func (q *Query) CountAll() (int, error)

CountAll 符合所有条件的记录数

func (*Query) Iter

func (q *Query) Iter() *Iter

Iter 模拟mgo.v2的Iter方法

func (*Query) Limit

func (q *Query) Limit(n int) *Query

Limit 模拟mgo.v2的Limit方法

func (*Query) One

func (q *Query) One(result interface{}) error

One 模拟mgo.v2的One方法

func (*Query) Select

func (q *Query) Select(selector interface{}) *Query

Select 模拟mgo.v2的Select方法

func (*Query) Skip

func (q *Query) Skip(n int) *Query

Skip 模拟mgo.v2的Skip方法

func (*Query) Sort

func (q *Query) Sort(fields ...string) *Query

Sort 模拟mgo.v2的Sort方法

type Safe

type Safe struct {
	W        int
	WMode    string
	WTimeout int
	FSync    bool
	J        bool
}

Safe 模拟mgo.v2的安全模式

type Session

type Session struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Session 模拟mgo.v2的Session

func Dial

func Dial(url string) (*Session, error)

Dial 模拟mgo.v2的Dial函数

func DialWithTimeout

func DialWithTimeout(url string, timeout time.Duration, poolMax int) (*Session, error)

DialWithTimeout 模拟mgo.v2的DialWithTimeout函数

func (*Session) Clone

func (s *Session) Clone() *Session

Clone 模拟mgo.v2的Clone方法

func (*Session) Close

func (s *Session) Close()

Close 模拟mgo.v2的Close方法

func (*Session) Copy

func (s *Session) Copy() *Session

Copy 模拟mgo.v2的Copy方法

func (*Session) DB

func (s *Session) DB(name string) *Database

DB 模拟mgo.v2的DB方法

func (*Session) DatabaseNames

func (s *Session) DatabaseNames() (names []string, err error)

DatabaseNames 模拟mgo.v2的DatabaseNames

func (*Session) Ping

func (s *Session) Ping() error

Ping 模拟mgo.v2的Ping方法

func (*Session) SetSafe

func (s *Session) SetSafe(safe *Safe)

SetSafe 模拟mgo.v2的SetSafe方法

func (*Session) SetSocketTimeout

func (s *Session) SetSocketTimeout(d time.Duration)

SetSocketTimeout 模拟mgo.v2的SetSocketTimeout方法

Jump to

Keyboard shortcuts

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