1BSON_GUIDES(3) libbson BSON_GUIDES(3)
2
3
4
6 bson_guides - Guides
7
9 bson_reader_t provides a streaming reader which can be initialized with
10 a filedescriptor or memory region. bson_writer_t provides a streaming
11 writer which can be initialized with a memory region. (Streaming BSON
12 to a file descriptor is not yet supported.)
13
14 Reading from a BSON Stream
15 bson_reader_t provides a convenient API to read sequential BSON docu‐
16 ments from a file-descriptor or memory buffer. The bson_reader_read()
17 function will read forward in the underlying stream and return a bson_t
18 that can be inspected and iterated upon.
19
20 #include <stdio.h>
21 #include <bson/bson.h>
22
23 int
24 main (int argc, char *argv[])
25 {
26 bson_reader_t *reader;
27 const bson_t *doc;
28 bson_error_t error;
29 bool eof;
30
31 reader = bson_reader_new_from_file ("mycollection.bson", &error);
32
33 if (!reader) {
34 fprintf (stderr, "Failed to open file.\n");
35 return 1;
36 }
37
38 while ((doc = bson_reader_read (reader, &eof))) {
39 char *str = bson_as_canonical_extended_json (doc, NULL);
40 printf ("%s\n", str);
41 bson_free (str);
42 }
43
44 if (!eof) {
45 fprintf (stderr,
46 "corrupted bson document found at %u\n",
47 (unsigned) bson_reader_tell (reader));
48 }
49
50 bson_reader_destroy (reader);
51
52 return 0;
53 }
54
55 See bson_reader_new_from_fd(), bson_reader_new_from_file(), and
56 bson_reader_new_from_data() for more information.
57
58 Writing a sequence of BSON Documents
59 bson_writer_t provides a convenient API to write a sequence of BSON
60 documents to a memory buffer that can grow with realloc(). The
61 bson_writer_begin() and bson_writer_end() functions will manage the
62 underlying buffer while building the sequence of documents.
63
64 This could also be useful if you want to write to a network packet
65 while serializing the documents from a higher level language, (but do
66 so just after the packets header).
67
68 #include <stdio.h>
69 #include <bson/bson.h>
70 #include <assert.h>
71
72 int
73 main (int argc, char *argv[])
74 {
75 bson_writer_t *writer;
76 bson_t *doc;
77 uint8_t *buf = NULL;
78 size_t buflen = 0;
79 bool r;
80 int i;
81
82 writer = bson_writer_new (&buf, &buflen, 0, bson_realloc_ctx, NULL);
83
84 for (i = 0; i < 10000; i++) {
85 r = bson_writer_begin (writer, &doc);
86 assert (r);
87
88 r = BSON_APPEND_INT32 (doc, "i", i);
89 assert (r);
90
91 bson_writer_end (writer);
92 }
93
94 bson_free (buf);
95
96 return 0;
97 }
98
99 See bson_writer_new() for more information.
100
102 Libbson provides routines for converting to and from the JSON format.
103 In particular, it supports the MongoDB extended JSON format.
104
105 Converting BSON to JSON
106 There are often times where you might want to convert a BSON document
107 to JSON. It is convenient for debugging as well as an interchange for‐
108 mat. To help with this, Libbson contains the functions bson_as_canoni‐
109 cal_extended_json() and bson_as_relaxed_extended_json(). The canonical
110 format preserves BSON type information for values that may have ambigu‐
111 ous representations in JSON (e.g. numeric types).
112
113 bson_t *b;
114 size_t len;
115 char *str;
116
117 b = BCON_NEW ("a", BCON_INT32 (1));
118
119 str = bson_as_canonical_extended_json (b, &len);
120 printf ("%s\n", str);
121 bson_free (str);
122
123 bson_destroy (b);
124
125 { "a" : { "$numberInt": "1" } }
126
127 The relaxed format prefers JSON primitives for numeric values and may
128 be used if type fidelity is not required.
129
130 bson_t *b;
131 size_t len;
132 char *str;
133
134 b = BCON_NEW ("a", BCON_INT32 (1));
135
136 str = bson_as_relaxed_extended_json (b, &len);
137 printf ("%s\n", str);
138 bson_free (str);
139
140 bson_destroy (b);
141
142 { "a" : 1 }
143
144 Converting JSON to BSON
145 Converting back from JSON is also useful and common enough that we
146 added bson_init_from_json() and bson_new_from_json().
147
148 The following example creates a new bson_t from the JSON string
149 {"a":1}.
150
151 bson_t *b;
152 bson_error_t error;
153
154 b = bson_new_from_json ("{\"a\":1}", -1, &error);
155
156 if (!b) {
157 printf ("Error: %s\n", error.message);
158 } else {
159 bson_destroy (b);
160 }
161
162 Streaming JSON Parsing
163 Libbson provides bson_json_reader_t to allow for parsing a sequence of
164 JSON documents into BSON. The interface is similar to bson_reader_t but
165 expects the input to be in the MongoDB extended JSON format.
166
167 /*
168 * Copyright 2013 MongoDB, Inc.
169 *
170 * Licensed under the Apache License, Version 2.0 (the "License");
171 * you may not use this file except in compliance with the License.
172 * You may obtain a copy of the License at
173 *
174 * http://www.apache.org/licenses/LICENSE-2.0
175 *
176 * Unless required by applicable law or agreed to in writing, software
177 * distributed under the License is distributed on an "AS IS" BASIS,
178 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
179 * See the License for the specific language governing permissions and
180 * limitations under the License.
181 */
182
183
184 /*
185 * This program will print each JSON document contained in the provided files
186 * as a BSON string to STDOUT.
187 */
188
189
190 #include <bson/bson.h>
191 #include <stdlib.h>
192 #include <stdio.h>
193
194
195 int
196 main (int argc, char *argv[])
197 {
198 bson_json_reader_t *reader;
199 bson_error_t error;
200 const char *filename;
201 bson_t doc = BSON_INITIALIZER;
202 int i;
203 int b;
204
205 /*
206 * Print program usage if no arguments are provided.
207 */
208 if (argc == 1) {
209 fprintf (stderr, "usage: %s FILE...\n", argv[0]);
210 return 1;
211 }
212
213 /*
214 * Process command line arguments expecting each to be a filename.
215 */
216 for (i = 1; i < argc; i++) {
217 filename = argv[i];
218
219 /*
220 * Open the filename provided in command line arguments.
221 */
222 if (0 == strcmp (filename, "-")) {
223 reader = bson_json_reader_new_from_fd (STDIN_FILENO, false);
224 } else {
225 if (!(reader = bson_json_reader_new_from_file (filename, &error))) {
226 fprintf (
227 stderr, "Failed to open \"%s\": %s\n", filename, error.message);
228 continue;
229 }
230 }
231
232 /*
233 * Convert each incoming document to BSON and print to stdout.
234 */
235 while ((b = bson_json_reader_read (reader, &doc, &error))) {
236 if (b < 0) {
237 fprintf (stderr, "Error in json parsing:\n%s\n", error.message);
238 abort ();
239 }
240
241 if (fwrite (bson_get_data (&doc), 1, doc.len, stdout) != doc.len) {
242 fprintf (stderr, "Failed to write to stdout, exiting.\n");
243 exit (1);
244 }
245 bson_reinit (&doc);
246 }
247
248 bson_json_reader_destroy (reader);
249 bson_destroy (&doc);
250 }
251
252 return 0;
253 }
254
255 Examples
256 The following example reads BSON documents from stdin and prints them
257 to stdout as JSON.
258
259 /*
260 * Copyright 2013 MongoDB, Inc.
261 *
262 * Licensed under the Apache License, Version 2.0 (the "License");
263 * you may not use this file except in compliance with the License.
264 * You may obtain a copy of the License at
265 *
266 * http://www.apache.org/licenses/LICENSE-2.0
267 *
268 * Unless required by applicable law or agreed to in writing, software
269 * distributed under the License is distributed on an "AS IS" BASIS,
270 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
271 * See the License for the specific language governing permissions and
272 * limitations under the License.
273 */
274
275
276 /*
277 * This program will print each BSON document contained in the provided files
278 * as a JSON string to STDOUT.
279 */
280
281
282 #include <bson/bson.h>
283 #include <stdio.h>
284
285
286 int
287 main (int argc, char *argv[])
288 {
289 bson_reader_t *reader;
290 const bson_t *b;
291 bson_error_t error;
292 const char *filename;
293 char *str;
294 int i;
295
296 /*
297 * Print program usage if no arguments are provided.
298 */
299 if (argc == 1) {
300 fprintf (stderr, "usage: %s [FILE | -]...\nUse - for STDIN.\n", argv[0]);
301 return 1;
302 }
303
304 /*
305 * Process command line arguments expecting each to be a filename.
306 */
307 for (i = 1; i < argc; i++) {
308 filename = argv[i];
309
310 if (strcmp (filename, "-") == 0) {
311 reader = bson_reader_new_from_fd (STDIN_FILENO, false);
312 } else {
313 if (!(reader = bson_reader_new_from_file (filename, &error))) {
314 fprintf (
315 stderr, "Failed to open \"%s\": %s\n", filename, error.message);
316 continue;
317 }
318 }
319
320 /*
321 * Convert each incoming document to JSON and print to stdout.
322 */
323 while ((b = bson_reader_read (reader, NULL))) {
324 str = bson_as_canonical_extended_json (b, NULL);
325 fprintf (stdout, "%s\n", str);
326 bson_free (str);
327 }
328
329 /*
330 * Cleanup after our reader, which closes the file descriptor.
331 */
332 bson_reader_destroy (reader);
333 }
334
335 return 0;
336 }
337
339 A stack-allocated bson_t contains a small internal buffer; it only
340 heap-allocates additional storage if necessary, depending on its data
341 size. Therefore if you forget to call bson_destroy on a stack-allocated
342 bson_t, it might or might not cause a leak that can be detected by val‐
343 grind during testing.
344
345 To catch all potential BSON data leaks in your code, configure the
346 BSON_MEMCHECK flag:
347
348 cmake -DCMAKE_C_FLAGS="-DBSON_MEMCHECK -g" .
349
350 With this flag set, every bson_t mallocs at least one byte. Run your
351 program's unittests with valgrind to verify all bson_t structs are
352 destroyed.
353
354 Set the environment variable MONGOC_TEST_VALGRIND to on to skip tim‐
355 ing-dependent tests known to fail with valgrind.
356
358 MongoDB, Inc
359
361 2017-present, MongoDB, Inc
362
363
364
365
3661.16.2 Feb 25, 2020 BSON_GUIDES(3)