BSON_STREAMING_BSON(3)
π BSON_STREAMING_BSON(3) π
okay so bestie, welcome to libbson's streaming era β¨ this is the BSON_STREAMING_BSON(3) page and it's literally all about moving BSON documents in and out like a boss.
So. bson_reader_t gives you a streaming reader that you can spin up with either a filedescriptor</> or a memory region. And bson_writer_t gives you a streaming writer that you can spin up with a memory region. π
and no, bestie, streaming BSON out to a file descriptor is not yet supported. we're manifesting it tho. π
β¨ READING FROM A BSON STREAM β¨
bson_reader_t is the convenient API for reading sequential BSON documents from a file-descriptor or a memory buffer. π¦ The bson_reader_read() function will read forward in the underlying stream and hand you back a bson_t that you can inspect and iterate upon. it's giving cursor but make it BSON.
#include <stdio.h>
#include <bson/bson.h>
int
main (int argc, char *argv[])
{
bson_reader_t *reader;
const bson_t *doc;
bson_error_t error;
bool eof;
reader = bson_reader_new_from_file ("mycollection.bson", &error);
if (!reader) {
fprintf (stderr, "Failed to open file.\n");
return 1;
}
while ((doc = bson_reader_read (reader, &eof))) {
char *str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
if (!eof) {
fprintf (stderr,
"corrupted bson document found at %u\n",
(unsigned) bson_reader_tell (reader));
}
bson_reader_destroy (reader);
return 0;
}
See bson_reader_new_from_fd(), bson_reader_new_from_file(), and bson_reader_new_from_data() for more information. π
π WRITING A SEQUENCE OF BSON DOCUMENTS π
bson_writer_t is the convenient API for writing a sequence of BSON documents to a memory buffer that can grow with realloc(). π₯ The bson_writer_begin() and bson_writer_end() functions will manage the underlying buffer while building the sequence of documents. they're the main characters here ngl.
This could also be useful if you want to write to a network packet while serializing the documents from a higher level language β (but do so just after the packets header). π
#include <stdio.h>
#include <bson/bson.h>
#include <assert.h>
int
main (int argc, char *argv[])
{
bson_writer_t *writer;
bson_t *doc;
uint8_t *buf = NULL;
size_t buflen = 0;
bool r;
int i;
writer = bson_writer_new (&buf, &buflen, 0, bson_realloc_ctx, NULL);
for (i = 0; i < 10000; i++) {
r = bson_writer_begin (writer, &doc);
assert (r);
r = BSON_APPEND_INT32 (doc, "i", i);
assert (r);
bson_writer_end (writer);
}
bson_free (buf);
return 0;
}
See bson_writer_new() for more information. πΈ
π AUTHOR π
MongoDB, Inc
π COPYRIGHT π
2017-present, MongoDB, Inc
and that's the whole page bestie, no cap π«Ά this was libbson version 1.26.0, dated Mar 31, 2024, and it ate. periodt. π
β¨π
π¦ where this page comes from
- ubuntu noble: libbson-doc 1.26.0-1.1ubuntu2 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms