mongodb

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: MIT Imports: 9 Imported by: 0

README

mongodb

简单使用案例

其一

package main

import (
	"fmt"
	"mongodb"
	"mongodb/bson"
	"strconv"
)

type User struct {
	ID   bson.ObjectID `bson:"_id" json:"_id"`
	Name string        `bson:"name" json:"name"`
}

func main() {
	uri := "mongodb://127.0.0.1:27017"

	mongoSession := mongodb.New(uri)
	mongoSession.SetPoolLimit(10)

	if cleanFunc, err := mongoSession.Connect(); err != nil {
		cleanFunc()
		fmt.Println("客户端连接出错:", err)
		return
	}

	//// 增
	if err := mongoSession.DB("test").Collection("users").Insert(bson.M{"name": "name"}); err != nil {
		fmt.Println("insert error:", err)
	}

	// 增多个
	var docs []interface{}
	for index := 0; index < 10; index++ {
		docs = append(docs, bson.M{"name": strconv.Itoa(index)})
	}

	if err := mongoSession.DB("test").Collection("users").InsertAll(docs); err != nil {
		fmt.Println("insertAll error:", err)
	}

	// 删
	if err := mongoSession.DB("test").Collection("users").Remove(bson.M{"name": "0"}); err != nil {
		fmt.Println("remove error:", err)
	}

	// 删多个
	if err := mongoSession.DB("test").Collection("users").RemoveAll(bson.M{"name": "1"}); err != nil {
		fmt.Println("removeAll error:", err)
	}

	// 改
	if err := mongoSession.DB("test").Collection("users").Update(bson.M{"name": "8"}, bson.M{"$set": bson.M{"name": "name"}}); err != nil {
		fmt.Println("update error:", err)
	}

	// 改多个
	info, err := mongoSession.DB("test").Collection("users").UpdateAll(bson.M{"name": "9"}, bson.M{"$set": bson.M{"name": "name_9"}})
	if err != nil {
		fmt.Println("updateAll error:", err)
	}
	fmt.Println("改多个的返回", info)

	// 查多个
	var resultAll []User
	if err := mongoSession.DB("test").Collection("users").Find(bson.M{}).All(&resultAll); err != nil {
		fmt.Println("find1 error:", err)
	}

	for _, r := range resultAll {
		fmt.Println("查出来了", r.Name)
	}

	var resultAlls []User
	// skip = page * limit
	if err := mongoSession.DB("test").Collection("users").Find(bson.M{"name": "name"}).Skip(2).Limit(2).All(&resultAlls); err != nil {
		fmt.Println("find2 error:", err)
	}

	for _, r := range resultAlls {
		fmt.Println("我又查出来了", r.ID, r.Name)
	}

	// 查
	var resultOne User
	if err := mongoSession.DB("test").Collection("users").Find(bson.M{"name": "name_9"}).One(&resultOne); err != nil {
		fmt.Println("one error:", err)
	}
	fmt.Println("我也查出来了", resultOne, resultOne.ID, resultOne.Name)

	// 统计数量
	count, err := mongoSession.DB("test").Collection("users").Count(bson.M{"name": "name"})
	if err != nil {
		fmt.Println("count error:", err)
	}
	fmt.Println("统计出来了", count)

}


其二

// cmd/main.go
package main

import (
    "fmt"
    "mongodb/options"
    "mongodb/start"
)

func main() {
    err := start.InitMongo()
    if err != nil {
        fmt.Println(err)
        return
    }
    options.SerSysApi = options.NewSysApiService(start.MongoSession)
    insert()
}

func insert() {
    options.SerSysApi.Insert()
}
// start/mongo.go
package start

import (
    "fmt"
    "mongodb"
)

var MongoSession *mongodb.MongoSession

func InitMongo() error {
    uri := "mongodb://127.0.0.1:27017"
    MongoSession = mongodb.New(uri)
    MongoSession.SetPoolLimit(10)
    
    if cleanFunc, err := MongoSession.Connect(); err != nil {
        cleanFunc()
        fmt.Println("客户端连接出错:", err)
        return fmt.Errorf("MongoDB client connection error: %v", err)
    }
    return nil
}

// options/mongo.go
package options

import (
    "fmt"
    "mongodb"
    "mongodb/bson"
)

type SysApiService struct {
    *mongodb.MongoSession
}

var SerSysApi = SysApiService{}

func (s *SysApiService) Insert() {
    // options\mongo.go
    //// 增
    if err := s.MongoSession.DB("test").Collection("users").Insert(bson.M{"name": "name"}); err != nil {
        fmt.Println("insert error:", err)
    }
}

package options

import "mongodb"

func NewSysApiService(session *mongodb.MongoSession) SysApiService {
    return SysApiService{
        MongoSession: session,
    }
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultTimeout = 60

Functions

This section is empty.

Types

type Collection

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

Collection mongo驱动程序集合

func (*Collection) Count

func (c *Collection) Count(selector interface{}) (int64, error)

Count 获取与筛选器匹配的文档数

func (*Collection) Find

func (c *Collection) Find(filter interface{}) *MongoSession

Find 按给定筛选器查找文档

func (*Collection) Insert

func (c *Collection) Insert(document interface{}) error

Insert 将单个文档插入到集合中

func (*Collection) InsertAll

func (c *Collection) InsertAll(documents []interface{}) error

InsertAll 插入提供的文档

func (*Collection) InsertAllWithResult

func (c *Collection) InsertAllWithResult(documents []interface{}) (result *mongo.InsertManyResult, err error)

InsertAllWithResult 插入提供的文档并返回insert many result

func (*Collection) InsertWithResult

func (c *Collection) InsertWithResult(document interface{}) (result *mongo.InsertOneResult, err error)

InsertWithResult 将单个文档插入到集合中,并返回insert one result

func (*Collection) Remove

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

Remove 从集合中删除单个文档

func (*Collection) RemoveAll

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

RemoveAll 从集合中删除多个文档

func (*Collection) RemoveID

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

RemoveID 按id从集合中删除单个文档

func (*Collection) Update

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

Update 更新集合中的单个文档

func (*Collection) UpdateAll

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

UpdateAll 更新集合中的多个文档

func (*Collection) UpdateID

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

UpdateID 按id更新集合中的单个文档

func (*Collection) UpdateWithResult

func (c *Collection) UpdateWithResult(selector interface{}, update interface{}, upsert ...bool) (result *mongo.UpdateResult, err error)

UpdateWithResult 更新集合中的单个文档并返回更新结果

type Database

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

Database mongo驱动程序数据库

func (*Database) C

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

C 设置集合名称

func (*Database) Collection

func (d *Database) Collection(collection string) *Collection

Collection 设置集合名称

func (*Database) CollectionNames

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

CollectionNames 返回数据库中存在的集合名称

type MongoSession

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

MongoSession mongo session

func New

func New(uri string) *MongoSession

New 创建mongo session

func (*MongoSession) All

func (s *MongoSession) All(result interface{}) error

All 返回多条数据

func (*MongoSession) C

func (s *MongoSession) C(collection string) *Collection

C Collection 集合名称名称

func (*MongoSession) Client

func (s *MongoSession) Client() *mongo.Client

Client 返回mongo 客户端

func (*MongoSession) Collection

func (s *MongoSession) Collection(collection string) *Collection

Collection 集合名称名称

func (*MongoSession) Connect

func (s *MongoSession) Connect() (func(), error)

Connect 连接 mongo 客户端

func (*MongoSession) DB

func (s *MongoSession) DB(db string) *Database

DB 设置数据库名

func (*MongoSession) Limit

func (s *MongoSession) Limit(limit int64) *MongoSession

Limit 设置限制

func (*MongoSession) One

func (s *MongoSession) One(result interface{}) error

One 返回一条数据

func (*MongoSession) Ping

func (s *MongoSession) Ping() error

Ping 验证客户端是否可以连接

func (*MongoSession) SetConnectTimeout

func (s *MongoSession) SetConnectTimeout(connectTimeout uint)

SetConnectTimeout 连接mongodb服务超时时间 秒

func (*MongoSession) SetPoolLimit

func (s *MongoSession) SetPoolLimit(limit uint64)

SetPoolLimit 指定服务器连接池的最大大小

func (*MongoSession) SetWithTimeOut

func (s *MongoSession) SetWithTimeOut(withTimeout uint)

SetWithTimeOut 操作超时时间 秒

func (*MongoSession) Skip

func (s *MongoSession) Skip(skip int64) *MongoSession

Skip 设置跳过

func (*MongoSession) Sort

func (s *MongoSession) Sort(sort interface{}) *MongoSession

Sort 设置排序

Jump to

Keyboard shortcuts

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