-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollection.go
45 lines (41 loc) · 1.26 KB
/
collection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package mongo
import (
"errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"google.golang.org/protobuf/proto"
)
func (b Client) GetCollection(database, collection string, databaseOptions *options.DatabaseOptions, collectionOptions *options.CollectionOptions) (*mongo.Collection, error) {
if b.client == nil {
return nil, errors.New("Mongo client must not be nil")
}
db, err := b.GetDatabase(database, databaseOptions)
if err != nil {
return nil, err
}
return db.Collection(collection, collectionOptions), nil
}
func (b Client) GetCollections(database string, nameOnly bool) (interface{}, error) {
if b.client == nil {
return nil, errors.New("Mongo client must not be nil")
}
db, err := b.GetDatabase(database, nil)
if err != nil {
return nil, err
}
cursor, err := db.ListCollections(Ctx(), bson.M{}, &options.ListCollectionsOptions{NameOnly: proto.Bool(nameOnly)})
if !cursor.Next(Ctx()) {
return nil, nil
}
var result []interface{}
err = cursor.All(Ctx(), &result)
return result, err
}
func (b Client) DropCollection(database string, collection string) error {
col, err := b.GetCollection(database, collection, nil, nil)
if err != nil {
return err
}
return col.Drop(Ctx())
}