diff --git a/.gitignore b/.gitignore index 5c75b7d..114804c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,4 @@ .vscode *.log gomod.sh -*_test.go /vendor/ diff --git a/LICENSE b/LICENSE deleted file mode 100644 index a0d0e5b..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 茂名聚合科技有限公司 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/app.go b/app.go deleted file mode 100644 index f83473b..0000000 --- a/app.go +++ /dev/null @@ -1,55 +0,0 @@ -package gomongo - -import ( - "context" - "errors" - "fmt" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" -) - -const Version = "1.0.7" - -type Client struct { - Db *mongo.Client // 驱动 - Dns string // 连接地址 - DatabaseName string // 库名 - collectionName string // 表名 -} - -// NewClient 实例化并链接数据库 -func NewClient(dns string, databaseName string) *Client { - // 连接到MongoDB - db, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(dns)) - if err != nil { - panic(fmt.Sprintf("数据库【mongo】连接失败:%v", err)) - } - - // 检查连接 - err = db.Ping(context.TODO(), nil) - if err != nil { - panic(fmt.Sprintf("数据库【mongo】连接服务器失败:%v", err)) - } - - if databaseName == "" { - return &Client{Db: db, Dns: dns} - } - return &Client{Db: db, Dns: dns, DatabaseName: databaseName} -} - -// NewDb 实例化并传入链接 -func NewDb(db *mongo.Client, databaseName string) *Client { - if databaseName == "" { - return &Client{Db: db} - } - return &Client{Db: db, DatabaseName: databaseName} -} - -// Close 关闭 -func (c *Client) Close() { - err := c.Db.Disconnect(context.TODO()) - if err != nil { - panic(errors.New(fmt.Sprintf("数据库【mongo】关闭失败:%v", err))) - } - return -} diff --git a/client.go b/client.go new file mode 100644 index 0000000..302345a --- /dev/null +++ b/client.go @@ -0,0 +1,57 @@ +package gomongo + +import ( + "context" + "errors" + "fmt" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +// Client 实例 +type Client struct { + db *mongo.Client // MongoDB驱动 + ctx context.Context // 上下文 + DatabaseName string // 库名 + collectionName string // 表名 + filterArr []queryFilter // 查询条件数组 + filter bson.D // 查询条件 +} + +// NewClient 实例化并链接数据库 +func NewClient(dns string) *Client { + + // 连接到MongoDB + db, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(dns)) + if err != nil { + panic(fmt.Sprintf("连接失败:%v", err)) + } + + // 检查连接 + err = db.Ping(context.TODO(), nil) + if err != nil { + panic(fmt.Sprintf("检查连接失败:%v", err)) + } + + return &Client{db: db, ctx: context.TODO()} +} + +// NewClientDb 实例化并传入链接 +func NewClientDb(db *mongo.Client) *Client { + return &Client{db: db, ctx: context.TODO()} +} + +// Close 关闭 +func (c *Client) Close() { + err := c.db.Disconnect(context.TODO()) + if err != nil { + panic(errors.New(fmt.Sprintf("关闭失败:%v", err))) + } + return +} + +// GetDbDriver 获取驱动 +func (c *Client) GetDbDriver() *mongo.Client { + return c.db +} diff --git a/curd.go b/curd.go index 6c883ef..309fe2d 100644 --- a/curd.go +++ b/curd.go @@ -2,9 +2,9 @@ package gomongo import ( "context" + "errors" "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + "log" "reflect" ) @@ -33,158 +33,121 @@ func (c *Client) Model(value interface{}) *Client { return c } -func (c *Client) Session() (session mongo.Session, err error) { - session, err = c.Db.StartSession() - return -} - -// InsertOne 插入单个文档 -func (c *Client) InsertOne(value interface{}) (result *mongo.InsertOneResult, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result, err = collection.InsertOne(context.TODO(), value) - return result, err -} - -// InsertMany 插入多个文档 -func (c *Client) InsertMany(values []interface{}) (result *mongo.InsertManyResult, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result, err = collection.InsertMany(context.TODO(), values) - return result, err -} - -// Delete 删除文档 -func (c *Client) Delete(filter interface{}) (int64, error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - count, err := collection.DeleteOne(context.TODO(), filter, nil) - return count.DeletedCount, err -} - -// DeleteMany 删除多个文档 -func (c *Client) DeleteMany(key string, value interface{}) (int64, error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - filter := bson.D{{key, value}} - count, err := collection.DeleteMany(context.TODO(), filter) - return count.DeletedCount, err -} - -// UpdateOne 更新单个文档 -// 修改字段的值($set) -// 字段增加值 inc($inc) -// 从数组中增加一个元素 push($push) -// 从数组中删除一个元素 pull($pull) -func (c *Client) UpdateOne(filter, update interface{}) (int64, error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result, err := collection.UpdateOne(context.TODO(), filter, update) - return result.UpsertedCount, err -} - -// UpdateMany 更新多个文档 -// 修改字段的值($set) -// 字段增加值 inc($inc) -// 从数组中增加一个元素 push($push) -// 从数组中删除一个元素 pull($pull) -func (c *Client) UpdateMany(filter, update interface{}) (int64, error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result, err := collection.UpdateMany(context.TODO(), filter, update) - return result.UpsertedCount, err -} - -// Find 查询 -func (c *Client) Find(filter interface{}, opts ...*options.FindOptions) (result *mongo.Cursor, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result, err = collection.Find(context.TODO(), filter, opts...) - return result, err -} - -// FindOne 查询单个文档 -func (c *Client) FindOne(filter interface{}) (result *mongo.SingleResult) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result = collection.FindOne(context.TODO(), filter) - return result -} +// CreateResult 返回查询结果 +type CreateResult struct { + InsertedID interface{} // 创建一条记录的ID + InsertedIDs []interface{} // 创建多条记录的ID +} + +// Create 创建数据 +func (c *Client) Create(values ...interface{}) (CreateResult, error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + + const ( + insertTypeOne = "one" + insertTypeMany = "many" + ) + + var ( + insertType string + insertDataOne interface{} + insertDataMany []interface{} + ) + + for _, value := range values { + switch v := value.(type) { + case map[string]interface{}: + case []map[string]interface{}: + case map[string]string: + case []map[string]string: + default: + sliceValue := reflect.Indirect(reflect.ValueOf(value)) + if sliceValue.Kind() == reflect.Slice { + insertType = insertTypeMany + size := sliceValue.Len() + for i := 0; i < size; i++ { + sv := sliceValue.Index(i) // 取出第i个元素 + elemValue := sv.Interface() // 原始数据 + insertDataMany = append(insertDataMany, elemValue) // 加入到数组中 + } + } else { + insertType = insertTypeOne + insertDataOne = v + } + } + } -// FindMany 查询多个文档 -func (c *Client) FindMany(filter interface{}) (result *mongo.Cursor, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result, err = collection.Find(context.TODO(), filter) - return result, err + if insertType == insertTypeOne { + result, err := collection.InsertOne(context.TODO(), insertDataOne) + return CreateResult{InsertedID: result.InsertedID}, err + } else if insertType == insertTypeMany { + result, err := collection.InsertMany(context.TODO(), insertDataMany) + return CreateResult{InsertedIDs: result.InsertedIDs}, err + } else { + return CreateResult{}, errors.New("values is empty") + } } -// FindManyByFilters 多条件查询 -func (c *Client) FindManyByFilters(filter interface{}) (result *mongo.Cursor, err error) { - collection, err := c.Db.Database(c.DatabaseName).Collection(c.collectionName).Clone() - result, err = collection.Find(context.TODO(), bson.M{"$and": filter}) - return result, err +// 查询条件 +type queryFilter struct { + Key string + Value interface{} } -// FindManyByFiltersSort 多条件查询支持排序 -func (c *Client) FindManyByFiltersSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) { - collection, err := c.Db.Database(c.DatabaseName).Collection(c.collectionName).Clone() - findOptions := options.Find() - findOptions.SetSort(Sort) - result, err = collection.Find(context.TODO(), filter, findOptions) - return result, err +// Where 条件 +func (c *Client) Where(key string, value interface{}) *Client { + log.Println("key", key) + log.Println("value", value) + c.filterArr = append(c.filterArr, queryFilter{key, value}) + c.filter = bson.D{{key, value}} + return c } -// FindCollection 查询集合文档 -func (c *Client) FindCollection(Limit int64) (result *mongo.Cursor, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - findOptions := options.Find() - findOptions.SetLimit(Limit) - result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions) - return result, err +// QueryResult 返回查询结果 +type QueryResult struct { + RowsAffected int // 返回找到的记录数 + Error error // 错误信息 } -// FindCollectionSort 查询集合文档支持排序 -func (c *Client) FindCollectionSort(Sort interface{}, Limit int64) (result *mongo.Cursor, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - findOptions := options.Find() - findOptions.SetSort(Sort) - findOptions.SetLimit(Limit) - result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions) - return result, err +// First 获取第一条记录(主键升序) +func (c *Client) First() *QueryResult { + return &QueryResult{} } -// FindManyCollectionSort 查询集合文档支持排序支持条件 -func (c *Client) FindManyCollectionSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - findOptions := options.Find() - findOptions.SetSort(Sort) - result, err = collection.Find(context.TODO(), filter, findOptions) - return result, err +// Take 获取一条记录,没有指定排序字段 +func (c *Client) Take(v interface{}) *QueryResult { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + //log.Printf("c.filterArr:%s\n", c.filterArr) + //log.Printf("c.filterArr:%v\n", c.filterArr) + //log.Printf("c.filterArr:%+v\n", c.filterArr) + //log.Printf("c.filter:%s\n", c.filter) + //log.Printf("c.filter:%v\n", c.filter) + //log.Printf("c.filter:%+v\n", c.filter) + err := collection.FindOne(context.TODO(), c.filter).Decode(v) + return &QueryResult{1, err} } -// CollectionCount 查询集合里有多少数据 -func (c *Client) CollectionCount() (name string, size int64) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - name = collection.Name() - size, _ = collection.EstimatedDocumentCount(context.TODO()) - return name, size +// Last 获取最后一条记录(主键降序) +func (c *Client) Last() *QueryResult { + return &QueryResult{} } -// CollectionDocuments 按选项查询集合 -// Skip 跳过 -// Limit 读取数量 -// sort 1 ,-1 . 1 为升序 , -1 为降序 -func (c *Client) CollectionDocuments(Skip, Limit int64, sort int, key string, value interface{}) (result *mongo.Cursor, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - SORT := bson.D{{"_id", sort}} - filter := bson.D{{key, value}} - findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip) - result, err = collection.Find(context.Background(), filter, findOptions) - return result, err -} +// Find 获取多条记录 +func (c *Client) Find(v interface{}) *QueryResult { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + log.Printf("c.filterArr:%s\n", c.filterArr) + log.Printf("c.filterArr:%v\n", c.filterArr) + log.Printf("c.filterArr:%+v\n", c.filterArr) + log.Printf("c.filter:%s\n", c.filter) + log.Printf("c.filter:%v\n", c.filter) + log.Printf("c.filter:%+v\n", c.filter) + cursor, err := collection.Find(context.TODO(), c.filter) + if err != nil { + return &QueryResult{0, err} + } -// AggregateByFiltersSort 统计分析 -func (c *Client) AggregateByFiltersSort(pipeline interface{}, opts ...*options.AggregateOptions) (result *mongo.Cursor, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - result, err = collection.Aggregate(context.TODO(), pipeline, opts...) - return result, err -} + // 结果遍历和赋值 + err = cursor.All(context.TODO(), v) -// CountDocumentsByFilters 统计数量 -func (c *Client) CountDocumentsByFilters(filter interface{}) (count int64, err error) { - collection := c.Db.Database(c.DatabaseName).Collection(c.collectionName) - count, err = collection.CountDocuments(context.TODO(), filter) - return count, err + return &QueryResult{cursor.RemainingBatchLength(), err} } diff --git a/go.mod b/go.mod index 1ef5e3a..c652b0d 100644 --- a/go.mod +++ b/go.mod @@ -12,14 +12,14 @@ require ( github.com/bitly/go-simplejson v0.5.0 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/golang/snappy v0.0.4 // indirect - github.com/klauspost/compress v1.15.3 // indirect + github.com/klauspost/compress v1.15.4 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect github.com/xdg-go/scram v1.1.1 // indirect github.com/xdg-go/stringprep v1.0.3 // indirect github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect - golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122 // indirect - golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect - golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect + golang.org/x/crypto v0.0.0-20220513210258-46612604a0f9 // indirect + golang.org/x/net v0.0.0-20220513224357-95641704303c // indirect + golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 // indirect golang.org/x/text v0.3.7 // indirect ) diff --git a/go.sum b/go.sum index 778947b..37d265e 100644 --- a/go.sum +++ b/go.sum @@ -14,8 +14,8 @@ github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEW github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/klauspost/compress v1.15.3 h1:wmfu2iqj9q22SyMINp1uQ8C2/V4M1phJdmH9fG4nba0= -github.com/klauspost/compress v1.15.3/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= +github.com/klauspost/compress v1.15.4 h1:1kn4/7MepF/CHmYub99/nNX8az0IJjfSOU/jbnTVfqQ= +github.com/klauspost/compress v1.15.4/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= @@ -47,16 +47,16 @@ go.mongodb.org/mongo-driver v1.9.1/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCu golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122 h1:NvGWuYG8dkDHFSKksI1P9faiVJ9rayE6l0+ouWVIDs8= -golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220513210258-46612604a0f9 h1:NUzdAbFtCJSXU20AOXgeqaUwg8Ypg4MPYmL+d+rsB5c= +golang.org/x/crypto v0.0.0-20220513210258-46612604a0f9/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA= -golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220513224357-95641704303c h1:nF9mHSvoKBLkQNQhJZNsc66z2UzAMUbLGjC95CF3pU0= +golang.org/x/net v0.0.0-20220513224357-95641704303c/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 h1:w8s32wxx3sY+OjLlv9qltkLU5yvJzxjjgiHWLjdIcw4= +golang.org/x/sync v0.0.0-20220513210516-0976fa681c29/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/json_test.go b/json_test.go new file mode 100644 index 0000000..2bda99e --- /dev/null +++ b/json_test.go @@ -0,0 +1,7 @@ +package gomongo + +import "testing" + +func TestJsonDecodeNoError(t *testing.T) { + t.Log(JsonDecodeNoError([]byte("{\"a\":1}"))) +} diff --git a/official.go b/official.go new file mode 100644 index 0000000..5982e2b --- /dev/null +++ b/official.go @@ -0,0 +1,164 @@ +package gomongo + +import ( + "context" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +func (c *Client) Session() (session mongo.Session, err error) { + session, err = c.db.StartSession() + return +} + +// InsertOne 插入单个文档 +func (c *Client) InsertOne(value interface{}) (result *mongo.InsertOneResult, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + result, err = collection.InsertOne(context.TODO(), value) + return result, err +} + +// InsertMany 插入多个文档 +func (c *Client) InsertMany(values []interface{}) (result *mongo.InsertManyResult, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + result, err = collection.InsertMany(context.TODO(), values) + return result, err +} + +// Delete 删除文档 +func (c *Client) Delete(filter interface{}) (int64, error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + count, err := collection.DeleteOne(context.TODO(), filter, nil) + return count.DeletedCount, err +} + +// DeleteMany 删除多个文档 +func (c *Client) DeleteMany(key string, value interface{}) (int64, error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + filter := bson.D{{key, value}} + count, err := collection.DeleteMany(context.TODO(), filter) + return count.DeletedCount, err +} + +// UpdateOne 更新单个文档 +// 修改字段的值($set) +// 字段增加值 inc($inc) +// 从数组中增加一个元素 push($push) +// 从数组中删除一个元素 pull($pull) +func (c *Client) UpdateOne(filter, update interface{}) (int64, error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + result, err := collection.UpdateOne(context.TODO(), filter, update) + return result.UpsertedCount, err +} + +// UpdateMany 更新多个文档 +// 修改字段的值($set) +// 字段增加值 inc($inc) +// 从数组中增加一个元素 push($push) +// 从数组中删除一个元素 pull($pull) +func (c *Client) UpdateMany(filter, update interface{}) (int64, error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + result, err := collection.UpdateMany(context.TODO(), filter, update) + return result.UpsertedCount, err +} + +// Find 查询 +//func (c *Client) Find(filter interface{}, opts ...*options.FindOptions) (result *mongo.Cursor, err error) { +// collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) +// result, err = collection.Find(context.TODO(), filter, opts...) +// return result, err +//} + +// FindOne 查询单个文档 +func (c *Client) FindOne(filter interface{}) (result *mongo.SingleResult) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + result = collection.FindOne(context.TODO(), filter) + return result +} + +// FindMany 查询多个文档 +func (c *Client) FindMany(filter interface{}) (result *mongo.Cursor, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + result, err = collection.Find(context.TODO(), filter) + return result, err +} + +// FindManyByFilters 多条件查询 +func (c *Client) FindManyByFilters(filter interface{}) (result *mongo.Cursor, err error) { + collection, err := c.db.Database(c.DatabaseName).Collection(c.collectionName).Clone() + result, err = collection.Find(context.TODO(), bson.M{"$and": filter}) + return result, err +} + +// FindManyByFiltersSort 多条件查询支持排序 +func (c *Client) FindManyByFiltersSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) { + collection, err := c.db.Database(c.DatabaseName).Collection(c.collectionName).Clone() + findOptions := options.Find() + findOptions.SetSort(Sort) + result, err = collection.Find(context.TODO(), filter, findOptions) + return result, err +} + +// FindCollection 查询集合文档 +func (c *Client) FindCollection(Limit int64) (result *mongo.Cursor, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + findOptions := options.Find() + findOptions.SetLimit(Limit) + result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions) + return result, err +} + +// FindCollectionSort 查询集合文档支持排序 +func (c *Client) FindCollectionSort(Sort interface{}, Limit int64) (result *mongo.Cursor, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + findOptions := options.Find() + findOptions.SetSort(Sort) + findOptions.SetLimit(Limit) + result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions) + return result, err +} + +// FindManyCollectionSort 查询集合文档支持排序支持条件 +func (c *Client) FindManyCollectionSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + findOptions := options.Find() + findOptions.SetSort(Sort) + result, err = collection.Find(context.TODO(), filter, findOptions) + return result, err +} + +// CollectionCount 查询集合里有多少数据 +func (c *Client) CollectionCount() (name string, size int64) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + name = collection.Name() + size, _ = collection.EstimatedDocumentCount(context.TODO()) + return name, size +} + +// CollectionDocuments 按选项查询集合 +// Skip 跳过 +// Limit 读取数量 +// sort 1 ,-1 . 1 为升序 , -1 为降序 +func (c *Client) CollectionDocuments(Skip, Limit int64, sort int, key string, value interface{}) (result *mongo.Cursor, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + SORT := bson.D{{"_id", sort}} + filter := bson.D{{key, value}} + findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip) + result, err = collection.Find(context.Background(), filter, findOptions) + return result, err +} + +// AggregateByFiltersSort 统计分析 +func (c *Client) AggregateByFiltersSort(pipeline interface{}, opts ...*options.AggregateOptions) (result *mongo.Cursor, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + result, err = collection.Aggregate(context.TODO(), pipeline, opts...) + return result, err +} + +// CountDocumentsByFilters 统计数量 +func (c *Client) CountDocumentsByFilters(filter interface{}) (count int64, err error) { + collection := c.db.Database(c.DatabaseName).Collection(c.collectionName) + count, err = collection.CountDocuments(context.TODO(), filter) + return count, err +} diff --git a/version.go b/version.go new file mode 100644 index 0000000..7d41df0 --- /dev/null +++ b/version.go @@ -0,0 +1,3 @@ +package gomongo + +const Version = "1.0.7" diff --git a/version_test.go b/version_test.go new file mode 100644 index 0000000..4e8bcd8 --- /dev/null +++ b/version_test.go @@ -0,0 +1,7 @@ +package gomongo + +import "testing" + +func TestVersion(t *testing.T) { + t.Log(Version) +} diff --git a/xml_test.go b/xml_test.go new file mode 100644 index 0000000..ed3bbe5 --- /dev/null +++ b/xml_test.go @@ -0,0 +1,11 @@ +package gomongo + +import ( + "fmt" + "testing" +) + +func TestXmlDecodeNoError(t *testing.T) { + resp := XmlDecodeNoError([]byte(`156252109993941149604514822022040106526851917616332410.012022-04-01 06:54:0012022-04-01 06:59:400`)) + fmt.Println(resp) +}