-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnosql.go
More file actions
92 lines (76 loc) · 2.41 KB
/
Copy pathnosql.go
File metadata and controls
92 lines (76 loc) · 2.41 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Package nosql implements wrappers for go.mongodb.org/mongo-driver
package nosql
import (
"context"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Database is a mongo.Database wrapper.
type Database struct {
*mongo.Database
}
// Collection is a mongo.Collection wrapper.
type Collection struct {
*mongo.Collection
}
// ManyResult contains Find results.
type ManyResult struct {
ctx context.Context
cursor *mongo.Cursor
err error
}
// NewDatabase creates a new Database instance.
func NewDatabase(db *mongo.Database) *Database { return &Database{Database: db} }
// Collection returns a handle for collection of database.
func (db *Database) Collection(name string, opts ...options.Lister[options.CollectionOptions]) *Collection {
return &Collection{
Collection: db.Database.Collection(name, opts...),
}
}
// FindMany finds all documents that match the filter and options.
func (c *Collection) FindMany(
ctx context.Context, filter interface{}, opts ...options.Lister[options.FindOptions],
) *ManyResult {
cursor, err := c.Collection.Find(ctx, filter, opts...)
return &ManyResult{
ctx: ctx,
cursor: cursor,
err: err,
}
}
// AggregateMany returns aggregate command results.
func (c *Collection) AggregateMany(
ctx context.Context, pipeline interface{}, opts ...options.Lister[options.AggregateOptions],
) *ManyResult {
cursor, err := c.Collection.Aggregate(ctx, pipeline, opts...)
return &ManyResult{
ctx: ctx,
cursor: cursor,
err: err,
}
}
// Cursor returns a underlying *mongo.Cursor.
func (a *ManyResult) Cursor() *mongo.Cursor { return a.cursor }
// Err returns a underlying error.
func (a *ManyResult) Err() error { return a.err }
// Decode decodes all found documents into a variable.
// The data parameter may be a pointer to an slice of struct.
// Also data parameter may be a pointer to an slice of pointers to a struct.
// For examples:
//
// var data1 []Struct // slice of struct
// err := collection.FindMany(ctx, bson.D{}).Decode(&data1) // pointer to an slice of ...
//
// var data2 []*Struct // slice of pointers to a struct
// err := collection.FindMany(ctx, bson.D{}).Decode(&data2) // pointer to an slice of ...
//
// If no documents are found, an empty slice is returned.
func (a *ManyResult) Decode(data interface{}) error {
if a.err != nil {
return a.err
}
if err := a.cursor.All(a.ctx, data); err != nil {
return err
}
return nil
}