-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
39 lines (28 loc) · 810 Bytes
/
mongo.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
package main
import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
//GetMongoDbConnection get connection of mongodb
func GetMongoDbConnection() (*mongo.Client, error) {
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.Background(), readpref.Primary())
if err != nil {
log.Fatal(err)
}
return client, nil
}
func getMongoDbCollection(DbName string, CollectionName string) (*mongo.Collection, error) {
client, err := GetMongoDbConnection()
if err != nil {
return nil, err
}
collection := client.Database(DbName).Collection(CollectionName)
return collection, nil
}