C Driver ,how to get Document Fileds Data objects without converting to json string

302 views
Skip to first unread message

meiry

unread,
Mar 1, 2016, 3:26:51 AM3/1/16
to mongodb-user
Hello 
Im using the C driver to make operations on mongoDB , when i do simple "find" operation 
shown here : 

while (mongoc_cursor_next (cursor, &doc)) {
     str
= bson_as_json (doc, NULL);
     printf
("%s\n", str);
     bson_free
(str);
}



i want to know if there is any way to get the bson objects without converting to json string as shown in the c++ driver shown here :
https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/bsoncxx/getting_values.cpp

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];


Thanks

Wan Bachtiar

unread,
Mar 9, 2016, 6:54:13 PM3/9/16
to mongodb-user

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.

Reply all
Reply to author
Forward
0 new messages