Provided by: libbson-doc_1.26.0-1.1ubuntu2_all 

LIBBSON
A Cross Platform BSON Library for C
Introduction
libbson builds, parses, and iterates BSON documents, the native data format of MongoDB. It also converts
BSON to and from JSON, and provides a platform compatibility layer for the MongoDB C Driver.
Tutorial
Using libbson In Your C Program
Include bson.h
All libbson's functions and types are available in one header file. Simply include bson.h:
hello_bson.c
#include <stdio.h>
#include <bson/bson.h>
int
main (int argc, const char **argv)
{
bson_t *b;
char *j;
b = BCON_NEW ("hello", BCON_UTF8 ("bson!"));
j = bson_as_canonical_extended_json (b, NULL);
printf ("%s\n", j);
bson_free (j);
bson_destroy (b);
return 0;
}
CMake
The libbson installation includes a CMake config-file package, so you can use CMake's find_package
command to import libbson's CMake target and link to libbson (as a shared library):
CMakeLists.txt
# Specify the minimum version you require.
find_package (bson-1.0 1.7 REQUIRED)
# The "hello_bson.c" sample program is shared among four tests.
add_executable (hello_bson ../../hello_bson.c)
target_link_libraries (hello_bson PRIVATE mongo::bson_shared)
You can also use libbson as a static library instead: Use the mongo::bson_static CMake target:
# Specify the minimum version you require.
find_package (bson-1.0 1.7 REQUIRED)
# The "hello_bson.c" sample program is shared among four tests.
add_executable (hello_bson ../../hello_bson.c)
target_link_libraries (hello_bson PRIVATE mongo::bson_static)
pkg-config
If you're not using CMake, use pkg-config on the command line to set header and library paths:
gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags libbson-1.0)
Or to statically link to libbson:
gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags libbson-static-1.0)
Creating a BSON Document
The bson_t structure
BSON documents are created using the bson_t structure. This structure encapsulates the necessary logic
for encoding using the BSON Specification. At the core, bson_t is a buffer manager and set of encoding
routines.
TIP:
BSON documents can live on the stack or the heap based on the performance needs or preference of the
consumer.
Let's start by creating a new BSON document on the stack. Whenever using libbson, make sure you #include
<bson/bson.h>.
bson_t b;
bson_init (&b);
This creates an empty document. In JSON, this would be the same as {}.
We can now proceed to adding items to the BSON document. A variety of functions prefixed with
bson_append_ can be used based on the type of field you want to append. Let's append a UTF-8 encoded
string.
bson_append_utf8 (&b, "key", -1, "value", -1);
Notice the two -1 parameters. The first indicates that the length of key in bytes should be determined
with strlen(). Alternatively, we could have passed the number 3. The same goes for the second -1, but for
value.
Libbson provides macros to make this less tedious when using string literals. The following two appends
are identical.
bson_append_utf8 (&b, "key", -1, "value", -1);
BSON_APPEND_UTF8 (&b, "key", "value");
Now let's take a look at an example that adds a few different field types to a BSON document.
bson_t b = BSON_INITIALIZER;
BSON_APPEND_INT32 (&b, "a", 1);
BSON_APPEND_UTF8 (&b, "hello", "world");
BSON_APPEND_BOOL (&b, "bool", true);
Notice that we omitted the call to bson_init(). By specifying BSON_INITIALIZER we can remove the need to
initialize the structure to a base state.
Sub-Documents and Sub-Arrays
To simplify the creation of sub-documents bson_append_document_begin() can be used to build a
sub-document using the parent's memory region as the destination buffer.
bson_t parent = BSON_INITIALIZER;
bson_t child;
bson_append_document_begin (&parent, "foo", 3, &child);
bson_append_int32 (&child, "baz", 3, 1);
bson_append_document_end (&parent, &child);
char *str = bson_as_relaxed_extended_json (&parent, NULL);
printf ("%s\n", str); // Prints: { "foo" : { "baz" : 1 } }
bson_free (str);
bson_destroy (&parent);
To simplify the creation of sub-arrays bson_array_builder_t can be used to build a sub-array using the
parent's memory region as the destination buffer.
bson_t parent = BSON_INITIALIZER;
bson_array_builder_t *bab;
bson_append_array_builder_begin (&parent, "foo", 3, &bab);
bson_array_builder_append_int32 (bab, 9);
bson_array_builder_append_int32 (bab, 8);
bson_array_builder_append_int32 (bab, 7);
bson_append_array_builder_end (&parent, bab);
char *str = bson_as_relaxed_extended_json (&parent, NULL);
printf ("%s\n", str); // Prints: { "foo" : [ 9, 8, 7 ] }
bson_free (str);
bson_destroy (&parent);
Simplified BSON C Object Notation
Creating BSON documents by hand can be tedious and time consuming. BCON, or BSON C Object Notation, was
added to allow for the creation of BSON documents in a format that looks closer to the destination
format.
The following example shows the use of BCON. Notice that values for fields are wrapped in the BCON_*
macros. These are required for the variadic processor to determine the parameter type.
bson_t *doc;
doc = BCON_NEW ("foo",
"{",
"int",
BCON_INT32 (1),
"array",
"[",
BCON_INT32 (100),
"{",
"sub",
BCON_UTF8 ("value"),
"}",
"]",
"}");
Creates the following document
{ "foo" : { "int" : 1, "array" : [ 100, { "sub" : "value" } ] } }
Handling Errors
Description
Many libbson functions report errors by returning NULL or -1 and filling out a bson_error_t structure
with an error domain, error code, and message.
• error.domain names the subsystem that generated the error.
• error.code is a domain-specific error type.
• error.message describes the error.
Some error codes overlap with others; always check both the domain and code to determine the type of
error.
─────────────────────────────────────────────────────────────────────────────────────────────
BSON_ERROR_JSON BSON_JSON_ERROR_READ_CORRUPT_JS bson_json_reader_t tried to
BSON_JSON_ERROR_READ_INVALID_PARAM parse invalid MongoDB
BSON_JSON_ERROR_READ_CB_FAILURE Extended JSON. Tried to
parse a valid JSON document
that is invalid as
MongoDBExtended JSON. An
internal callback failure
during JSON parsing.
─────────────────────────────────────────────────────────────────────────────────────────────
BSON_ERROR_READER BSON_ERROR_READER_BADFD bson_json_reader_new_from_file()
could not open the file.
┌───────────────────┬────────────────────────────────────┬──────────────────────────────────┐
│ │ │ │
ObjectIDs│ │ │ │
--
AUTHOR
MongoDB, Inc
COPYRIGHT
2017-present, MongoDB, Inc
1.26.0 Mar 31, 2024 BSON_REFERENCE(3)