@@ -11,6 +11,13 @@ import (
1111 "go.mongodb.org/mongo-driver/mongo/options"
1212)
1313
14+ // start-sample-struct
15+ type MyStruct struct {
16+ MyProperty string
17+ }
18+
19+ // end-sample-struct
20+
1421func main () {
1522 var uri string
1623 if uri = os .Getenv ("MONGODB_URI" ); uri == "" {
@@ -28,19 +35,18 @@ func main() {
2835 }
2936 }()
3037
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" )
3439 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" },
3843 }
3944
4045 result , err := coll .InsertMany (context .TODO (), docs )
4146 if err != nil {
4247 panic (err )
4348 }
49+
4450 fmt .Printf ("Number of documents inserted: %d\n " , len (result .InsertedIDs ))
4551
4652 fmt .Println ("Cursor Elements:" )
@@ -54,7 +60,7 @@ func main() {
5460 // begin close
5561 defer cursor .Close (context .TODO ())
5662 // end close
57-
63+
5864 for cursor .Next (context .TODO ()) {
5965 // begin current
6066 fmt .Println (cursor .Current )
@@ -73,22 +79,22 @@ func main() {
7379
7480 fmt .Println ("Cursor.All():" )
7581 {
76- // begin find
82+ // begin cursor def
7783 cursor , err := coll .Find (context .TODO (), bson.D {})
7884 if err != nil {
7985 panic (err )
8086 }
81- // end find
87+ // end cursor def
8288
8389 defer cursor .Close (context .TODO ())
84-
90+
8591 // begin cursor all
86- var results []bson. D
92+ var results []MyStruct
8793 if err = cursor .All (context .TODO (), & results ); err != nil {
8894 panic (err )
8995 }
9096 for _ , result := range results {
91- fmt .Println ( result )
97+ fmt .Printf ( "%+v \n " , result )
9298 }
9399 // end cursor all
94100 }
@@ -104,11 +110,11 @@ func main() {
104110
105111 // begin cursor next
106112 for cursor .Next (context .TODO ()) {
107- var result bson. D
113+ var result MyStruct
108114 if err := cursor .Decode (& result ); err != nil {
109115 log .Fatal (err )
110116 }
111- fmt .Println ( result )
117+ fmt .Printf ( "%+v \n " , result )
112118 }
113119 if err := cursor .Err (); err != nil {
114120 log .Fatal (err )
@@ -128,11 +134,11 @@ func main() {
128134 // begin cursor try next
129135 for {
130136 if cursor .TryNext (context .TODO ()) {
131- var result bson. D
137+ var result MyStruct
132138 if err := cursor .Decode (& result ); err != nil {
133139 log .Fatal (err )
134140 }
135- fmt .Println ( result )
141+ fmt .Printf ( "%+v \n " , result )
136142 continue
137143 }
138144
0 commit comments