-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo-go-driver.go
85 lines (70 loc) · 1.58 KB
/
mongo-go-driver.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
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
//
// mongo-go-driver.go
//
// Created by Arka Mukherjee on 27/02/20.
//
//
package main
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/bsonx"
)
type TestMongoStruct struct {
Foo string `bson:"foo"`
Bar string `bson:"bar"`
Baz int `bson:"baz"`
}
func main() {
//const storing DB details
const (
Database = "test"
Collection = "users"
)
ctx := context.TODO()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
panic(err)
}
testMongoData := TestMongoStruct{
Foo: "alice",
Bar: "bob",
Baz: 123,
}
// Collection data
c := client.Database("test").Collection("users")
/* CRUD CALLS */
//Inserting Data
_, err = c.InsertOne(ctx, &testMongoData)
if err != nil {
panic(err)
}
//Finding Data
var model TestMongoStruct
err = c.FindOne(ctx, bson.M{"foo": "alice"}).Decode(&model)
//Find and Modify
a, err := primitive.ObjectIDFromHex("XXXXXXXXXX")
if err == nil {
_ = c.FindOneAndUpdate(ctx, bson.M{"_id": a}, bson.M{"$set": bson.M{"foo": "berncastel"}})
}
//Update
update := bson.M{}
update = bson.M{
"$inc": bson.M{
"baz": 123,
},
}
_, err = c.UpdateOne(ctx, bson.M{"_id": a}, update)
//Find with projection
err = c.FindOne(ctx, bson.M{
"baz": 246,
}, options.FindOne().SetProjection(bsonx.Doc{{"baz", bsonx.Int32(1)}})).Decode(model)
//Delete
_, err = c.DeleteOne(ctx, bson.M{"_id": a})
if err != nil {
panic(err)
}
}