@@ -11,6 +11,13 @@ import (
11
11
"go.mongodb.org/mongo-driver/mongo/options"
12
12
)
13
13
14
+ // start-sample-struct
15
+ type MyStruct struct {
16
+ MyProperty string
17
+ }
18
+
19
+ // end-sample-struct
20
+
14
21
func main () {
15
22
var uri string
16
23
if uri = os .Getenv ("MONGODB_URI" ); uri == "" {
@@ -28,19 +35,18 @@ func main() {
28
35
}
29
36
}()
30
37
31
- client .Database ("tea" ).Collection ("ratings" ).Drop (context .TODO ())
32
-
33
- coll := client .Database ("tea" ).Collection ("ratings" )
38
+ coll := client .Database ("db" ).Collection ("sample_data" )
34
39
docs := []interface {}{
35
- bson. D {{ "type" , "Masala" }, { "rating" , 10 } },
36
- bson. D {{ "type" , "Earl Grey" }, { "rating" , 5 } },
37
- bson. D {{ "type" , "Assam" }, { "rating" , 7 } },
40
+ MyStruct { MyProperty : "abc" },
41
+ MyStruct { MyProperty : "def" },
42
+ MyStruct { MyProperty : "ghi" },
38
43
}
39
44
40
45
result , err := coll .InsertMany (context .TODO (), docs )
41
46
if err != nil {
42
47
panic (err )
43
48
}
49
+
44
50
fmt .Printf ("Number of documents inserted: %d\n " , len (result .InsertedIDs ))
45
51
46
52
fmt .Println ("Cursor Elements:" )
@@ -54,7 +60,7 @@ func main() {
54
60
// begin close
55
61
defer cursor .Close (context .TODO ())
56
62
// end close
57
-
63
+
58
64
for cursor .Next (context .TODO ()) {
59
65
// begin current
60
66
fmt .Println (cursor .Current )
@@ -73,22 +79,22 @@ func main() {
73
79
74
80
fmt .Println ("Cursor.All():" )
75
81
{
76
- // begin find
82
+ // begin cursor def
77
83
cursor , err := coll .Find (context .TODO (), bson.D {})
78
84
if err != nil {
79
85
panic (err )
80
86
}
81
- // end find
87
+ // end cursor def
82
88
83
89
defer cursor .Close (context .TODO ())
84
-
90
+
85
91
// begin cursor all
86
- var results []bson. D
92
+ var results []MyStruct
87
93
if err = cursor .All (context .TODO (), & results ); err != nil {
88
94
panic (err )
89
95
}
90
96
for _ , result := range results {
91
- fmt .Println ( result )
97
+ fmt .Printf ( "%+v \n " , result )
92
98
}
93
99
// end cursor all
94
100
}
@@ -104,11 +110,11 @@ func main() {
104
110
105
111
// begin cursor next
106
112
for cursor .Next (context .TODO ()) {
107
- var result bson. D
113
+ var result MyStruct
108
114
if err := cursor .Decode (& result ); err != nil {
109
115
log .Fatal (err )
110
116
}
111
- fmt .Println ( result )
117
+ fmt .Printf ( "%+v \n " , result )
112
118
}
113
119
if err := cursor .Err (); err != nil {
114
120
log .Fatal (err )
@@ -128,11 +134,11 @@ func main() {
128
134
// begin cursor try next
129
135
for {
130
136
if cursor .TryNext (context .TODO ()) {
131
- var result bson. D
137
+ var result MyStruct
132
138
if err := cursor .Decode (& result ); err != nil {
133
139
log .Fatal (err )
134
140
}
135
- fmt .Println ( result )
141
+ fmt .Printf ( "%+v \n " , result )
136
142
continue
137
143
}
138
144
0 commit comments