forked from SourceFellows/gobuch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (72 loc) · 1.68 KB
/
main.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
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Customer struct {
FirstName string
LastName string
CreditCard CreditCard
}
type CreditCard struct {
Number string
}
func main() {
client, err := mongo.NewClient(
options.Client().
ApplyURI("mongodb://mongorootuser:mongorootpw@localhost:27017"))
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
err = client.Ping(ctx, readpref.Primary())
if err != nil {
panic(err)
}
collection := client.Database("shop").Collection("customer")
customer := Customer{FirstName: "Hans", LastName: "wurst"}
customer.CreditCard = CreditCard{Number: "123-123-123"}
collection.InsertOne(ctx, customer)
cursor, err := collection.Find(ctx, bson.D{{"firstname", "Hans"}})
if err != nil {
panic(err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var result bson.M
err := cursor.Decode(&result)
if err != nil {
panic(err)
}
fmt.Printf("result is %v\n", result)
}
if err := cursor.Err(); err != nil {
panic(err)
}
filter := bson.D{{"firstname", "Hans"}}
updated := bson.M{
"$set": Customer{FirstName: "Peter", LastName: "Lustig"},
}
res, err := collection.UpdateOne(ctx, filter, updated)
if err != nil {
panic(err)
}
fmt.Println(res.MatchedCount)
collection.FindOneAndUpdate(ctx, filter, updated)
collection.FindOneAndDelete(ctx, filter)
}