while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}auto doc = build_doc.view();
// Once we have the document view, we can use ["key"] or [index] notation to reach into nested
// documents or arrays.
auto awards = doc["awards"];
auto first_award_year = awards[0]["year"];
auto second_award_year = doc["awards"][1]["year"];
auto last_name = doc["name"]["last"];
// If the key doesn't exist, or index is out of bounds, we get invalid elements.
auto invalid1 = doc["name"]["middle"];
auto invalid2 = doc["contribs"][1000];
Hi Meiry,
You could utilise bson_iter_t to iterate through the elements of a bson_t.
For example, to iterate through a bson document and find a specific field name that contains a string value:
bson_iter_t iter;
bson_type_t type;
const bson_value_t *value;
while (mongoc_cursor_next (cursor, &doc)) {
if (bson_iter_init (&iter, doc) && bson_iter_find (&iter, "fieldName")) {
printf ("Found field name key: %s\n", bson_iter_key (&iter));
type = bson_iter_type (&iter);
printf("The type: %d\n", (int)type);
value = bson_iter_value (&iter);
printf("String value is: %s", value->value.v_utf8.str);
}
}
See Available Types to find out the corresponding numbers to BSON types.
You can also iterate through using bson_iter_next. As an example:
if (bson_iter_init(&iter, doc)) {
while (bson_iter_next(&iter)) {
key = bson_iter_key(&iter);
...
Also see Parsing and Iterating BSON documents for more examples.
Kind regards,
Wan.