...
1
2
3
4
5
6
7 package bson_test
8
9 import (
10 "fmt"
11 "time"
12
13 "go.mongodb.org/mongo-driver/bson"
14 )
15
16
17 func ExampleRaw_unmarshal() {
18 b, err := bson.Marshal(bson.M{
19 "Word": "beach",
20 "Synonyms": bson.A{"coast", "shore", "waterfront"},
21 })
22 if err != nil {
23 panic(err)
24 }
25
26 var res struct {
27 Word string
28 Synonyms bson.Raw
29 }
30
31 err = bson.Unmarshal(b, &res)
32 if err != nil {
33 panic(err)
34 }
35 elems, err := res.Synonyms.Elements()
36 if err != nil {
37 panic(err)
38 }
39 fmt.Printf("%s, synonyms count: %d\n", res.Word, len(elems))
40
41
42 }
43
44
45 func ExampleRaw_marshal() {
46 precomputed, err := bson.Marshal(bson.M{"Precomputed": true})
47 if err != nil {
48 panic(err)
49 }
50
51 msg := struct {
52 Message string
53 Metadata bson.Raw
54 }{
55 Message: "Hello World!",
56 Metadata: precomputed,
57 }
58
59 b, err := bson.Marshal(msg)
60 if err != nil {
61 panic(err)
62 }
63
64 fmt.Println(bson.Raw(b).String())
65
66
67 }
68
69
70 func ExampleRawValue_unmarshal() {
71 b1, err := bson.Marshal(bson.M{
72 "Format": "UNIX",
73 "Timestamp": 1675282389,
74 })
75 if err != nil {
76 panic(err)
77 }
78
79 b2, err := bson.Marshal(bson.M{
80 "Format": "RFC3339",
81 "Timestamp": time.Unix(1675282389, 0).Format(time.RFC3339),
82 })
83 if err != nil {
84 panic(err)
85 }
86
87 for _, b := range [][]byte{b1, b2} {
88 var res struct {
89 Format string
90 Timestamp bson.RawValue
91 }
92
93 err = bson.Unmarshal(b, &res)
94 if err != nil {
95 panic(err)
96 }
97
98 var t time.Time
99 switch res.Format {
100 case "UNIX":
101 t = time.Unix(res.Timestamp.AsInt64(), 0)
102 case "RFC3339":
103 t, err = time.Parse(time.RFC3339, res.Timestamp.StringValue())
104 if err != nil {
105 panic(err)
106 }
107 }
108 fmt.Println(res.Format, t.Unix())
109 }
110
111
112
113
114 }
115
116
117 func ExampleRawValue_marshal() {
118 t, val, err := bson.MarshalValue("Precomputed message!")
119 if err != nil {
120 panic(err)
121 }
122 precomputed := bson.RawValue{
123 Type: t,
124 Value: val,
125 }
126
127 msg := struct {
128 Message bson.RawValue
129 Time time.Time
130 }{
131 Message: precomputed,
132 Time: time.Unix(1675282389, 0),
133 }
134
135 b, err := bson.Marshal(msg)
136 if err != nil {
137 panic(err)
138 }
139
140 fmt.Println(bson.Raw(b).String())
141
142
143 }
144
View as plain text