-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
57 lines (44 loc) · 1019 Bytes
/
db.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
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
// "fmt"
"os"
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
)
var (
dbName = "db"
dbColl = "q_collection"
)
// Client mongodb client
var Client *mongo.Client
// MongoDBInit init mongodb
func MongoDBInit() {
var err error
clientOptions := options.Client().ApplyURI(os.Getenv("MONGO_URI"))
Client, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
}
func find(ag bson.D) []Quote {
collection := Client.Database(dbName).Collection(dbColl)
cur, _ := collection.Aggregate(context.TODO(), mongo.Pipeline{ag})
var result []Quote
for cur.Next(context.TODO()) {
var elem Quote
err := cur.Decode(&elem)
if err != nil {
log.Fatal("Something Went Wrong!")
}
result = append(result, elem)
}
if err := cur.Err(); err != nil {
log.Fatal("Something Went Wrong!")
}
// Close the cursor once finished
cur.Close(context.TODO())
return result
}