Mongo C++ Examples

907 views
Skip to first unread message

aks S

unread,
Feb 9, 2018, 8:03:46 PM2/9/18
to mongodb-user
Hi David,

I am very new to Mongo and I am coding in C++. I feel there is lack of api documentation and example usage programs . 
In attached screenshot I am just trying to iterate through a collection . Not sure how to iterate through .

Could you please advise if there is an official page to see the sample programs and api usage ?

Regards,
Aks
mongo.png

Wan Bachtiar

unread,
Feb 12, 2018, 6:31:24 PM2/12/18
to mongodb-user

Could you please advise if there is an official page to see the sample programs and api usage ?

Hi,

You can find a quick start tutorial on MongoDB C++ Driver v3: Tutorial.
There are also full code examples on mongo-cxx-driver: examples that may be useful.

In attached screenshot I am just trying to iterate through a collection . Not sure how to iterate through

Based on your snippet, it looks like you’re trying to iterate on keys and values for each document returned by the cursor.
See an example snippet below:

    // Find all in a collection
    auto cursor = collection.find({});
    for (auto&& doc : cursor) {
        for (bsoncxx::document::element element : doc)
        {
            bsoncxx::stdx::string_view field_key{element.key()};
            // Only for string UTF8 value
            if (element.type() == bsoncxx::type::k_utf8){
                std::cout << "key = " << field_key << " , value = " << element.get_utf8().value.to_string() << std::endl;
            }
        }
        std::cout<<std::endl;
    }

If the value in the element is not a string (utf8) then the above code will throw an instance of bsoncxx::exception. See also bsoncxx::types.

You may also find bsoncxx::view_and_value.cpp - an example on iterating over elements in a bson document useful.

void DataAccessService::FindInCollection()

If you’re wanting to query a document in a collection, please see Tutorial: Find a single document in a collection

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages