mongocxx bsoncxx new c++11 driver: Basic Question: Extracting string from document

1,695 views
Skip to first unread message

javantamt

unread,
May 26, 2016, 10:58:45 AM5/26/16
to mongodb-user
Hey everebody,

today the aim is to extract a string out of the database.
In
bsoncxx/test/bson_get_values.cpp

it's clearly described how to extract any other value out of the bson document. Int, bool, ...
But I realy would like to have a simpel string.

Doing something like this works perfectialy:

bsoncxx::document::value newDocument = document{}
   
<< "stuff" << TheJobView["source"]["url"].get_value()
   
<< finalize;

But I don't know how to get the string out of this.

  bsoncxx::stdx::optional<bsoncxx::document::value> vTheJob;
 
GetADataset(&vTheJob);
  bsoncxx
::document::view  TheJobView = vTheJob.value().view();
  std
::string strLocationSource =  TheJobView["source"]["url"].get_value();

The compiler is telling me to stop my attempt immdiately:

 error: conversion from bsoncxx::v_noabi::document::element
 to non
-scalar type
 
std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
 requested

My JSON looks like this:
{
 
"_id" : ObjectId("5746db57b6a7d11cb64cbba1"),
 
"source" : {
   
"url" : "www.mongodb.com",
   
"some": "more"
   
}
}


javantamt

unread,
May 26, 2016, 3:25:53 PM5/26/16
to mongodb-user
  bsoncxx::document::value ismaster = bsoncxx::builder::stream::document{} << "James" << "I will do my very best!" << finalize;
  bsoncxx
::document::view  TheJobView = ismaster.view();
  std
::string MyString = TheJobView["ismaster"].get_utf8().value.to_string();

  std
::cout << MyString << std::endl;

javantamt

unread,
May 26, 2016, 4:16:13 PM5/26/16
to mongodb-user
 
forgot to check the type. I dont't kinow how to make this ckeck more easy. But this works.
Maybe some of you having a better idea?

 bsoncxx
::document::value ismaster = bsoncxx::builder::stream::document{} << "ismaster" << "hubs" << finalize;
  bsoncxx
::document::view  TheJobView = ismaster.view();
  std
::string MyString;
 
auto MyType = TheJobView["ismaster"].type();

 
auto hey = bsoncxx::types::b_utf8{"hello"};
 
 
if (hey.type_id == TheJobView["ismaster"].type() )
 
{

   
MyString = TheJobView["ismaster"].get_utf8().value.to_string();

   
// going to do the upper without prechecking will cause a SIGABTR,
   
// a Signal generatet by this process send to cernal which is
   
// sending same signal back. Recieving this signal is suicide.
   
// Described in here as undefined behaviour:
   
// https://mongodb.github.io/mongo-cxx-driver/classbsoncxx_1_1types_1_1value.html#a215272e9bca2780e88c036a59e51b90e
   
// maybe this document could give a hint in the future how to check type?
   
    std
::cout << MyString << std::endl;
 
}



Am Donnerstag, 26. Mai 2016 16:58:45 UTC+2 schrieb javantamt:

Andrew Morrow

unread,
May 26, 2016, 4:43:05 PM5/26/16
to mongod...@googlegroups.com

Hi -

You can get the type of a bsoncxx::document::element by calling the bsoncxx::document::element::type method, and then compare the returned value to one of the enumeration values from bsoncxx/types.h, like bsoncxx::type::k_utf8. As you noticed, each of the b_ prefixed types in the bsoncxx::types namespace has a public static constexpr member named type_id. Since the type_id member is static, you don't need to first create an object to obtain it. Here is a simpler version (not compiled) of your code:

auto TheJobView = ...;

auto ismasterElement = TheJobView["ismaster"];
if (!ismasterElement) {
    // we didn't get the field we expected
    throw std::logic_error("didn't find ismaster field in command response");
}
 
if (ismasterElement.type() != bsoncxx::types::b_utf8::type_id) {
    // we got the field, but it isn't the type we expected
    throw std::logic_error("ismaster field in command response was wrong type");
}

// OK, if we got here we have the field and we know it is of 
// type k_utf8, so it is safe to call get_utf8 on it.
auto MyString = isMasterElement.get_utf8().value.to_string();
std::cout << MyString << std::endl;

Can you try something more like this? I think you will find it works better.

Thanks,
Andrew


--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: https://docs.mongodb.org/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/7c7fa1d0-a4ed-40bd-9de8-7e5acdbd5fd1%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

javantamt

unread,
May 27, 2016, 8:45:54 AM5/27/16
to mongodb-user
nice one!
I was looking for a solution like that.
thank you for the solution and the quick support!


Am Donnerstag, 26. Mai 2016 16:58:45 UTC+2 schrieb javantamt:

sarthak agarwal

unread,
Jul 10, 2018, 8:51:38 AM7/10/18
to mongodb-user
Hello guys,

How do we handle array in this case. I want to store the value in a array and then get the size of that array and access its elements using [] operator. liek this 

bsoncxx::document::element edges_element = current_node_view["connects_to"];
auto = edges_element.get_array();
for(int i=0; i<edges.size(); i++){
     cout << edges[i] << "\t";
}cout << endl;

but it gives the following error - 
dijkstras.cpp: In function ‘int dijikstras(mongocxx::v_noabi::collection, int, int)’:
dijkstras.cpp:60:58: error: conversion from ‘bsoncxx::v_noabi::types::b_array’ to non-scalar type ‘bsoncxx::v_noabi::types::value’ requested
    bsoncxx::types::value edges = edges_element.get_array();
                                                          ^
dijkstras.cpp:61:25: error: ‘class bsoncxx::v_noabi::types::value’ has no member named ‘size’
    for(int i=0; i<edges.size(); i++){
                         ^
dijkstras.cpp:62:18: error: no match for ‘operator[]’ (operand types are ‘bsoncxx::v_noabi::types::value’ and ‘int’)
     cout << edges[i] << "\t";


can you please help me

Wan Bachtiar

unread,
Jul 11, 2018, 2:41:23 AM7/11/18
to mongodb-user

I want to store the value in a array and then get the size of that array and access its elements using [] operator

Hi Sarthak,

Please open a new discussion thread instead of replying to an old thread from 2016.

Based on the information you provided, once you have queried a document, if it’s an array you can access the element(s) as the following example:

bsoncxx::document::element edges_elements = current_node_view["connects_to"];

if (edges_elements && edges_elements.type() == bsoncxx::type::k_array){
    bsoncxx::array::view subarray{edges_elements.get_array().value};
    for (bsoncxx::array::element element : subarray){
        // Assuming that the element value is String.
        std::cout<< element.get_utf8().value << "\t";
    }
}

If you have further questions, please open a new discussion thread with the following information:

  • MongoDB C++ driver version
  • The example document to show the structure and value types.

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages