BSON documents are lazily parsed as necessary. To begin parsing a BSON document, use one of the provided Libbson functions to create a new bson_t from existing data such as bson_new_from_data(). This will make a copy of the data so that additional mutations may occur to the BSON document.
If you only want to parse a BSON document and have no need to mutate it, you may use bson_init_static() to avoid making a copy of the data.
did not match \n");
return;
}
bson_destroy (b);]]>
Only two checks are performed when creating a new bson_t from an existing buffer. First, the document must begin with the buffer length, matching what was expected by the caller. Second, the document must end with the expected trailing \0
byte.
To parse the document further we use a bson_iter_t to iterate the elements within the document. Let's print all of the field names in the document.
Converting a document to JSON uses a bson_iter_t and bson_visitor_t to iterate all fields of a BSON document recursively and generate a UTF-8 encoded JSON string.
Libbson provides convenient sub-iterators to dive down into a sub-document or sub-array. Below is an example that will dive into a sub-document named "foo" and print it's field names.
Using the bson_iter_recurse() function exemplified above, bson_iter_find_descendant() can find a field for you using the MongoDB style path notation such as "foo.bar.0.baz".
Let's create a document like {"foo": {"bar": [{"baz: 1}]}}
and locate the "baz"
field.
If all you want to do is validate that a BSON document is valid, you can use bson_validate().
See the bson_validate() documentation for more information and examples.