mongocxx bsoncxx new c++11 driver: Extracting Values from bson without knowing the key's name

755 views
Skip to first unread message

javantamt

unread,
Jun 4, 2016, 3:03:02 PM6/4/16
to mongodb-user
Hey there,
I'm reciving a JSON from an application. I know the structure, but not the names of the keys. I'm going to extract the URL's, which are placed in the arrays.
But I don't know the names of the key's of the subdocument. So I can't access them like here:
auto ArrayToExtract =MayDocumentView["file"][???];

Using numbers is assuming an offset in an array and no key. It's return value is a bsoncxx::array::element and not a document::element.

// My JSON
{
   
"file": {
       
"khjasdnkas": ["MyURL_1t", "MyURL_2t", "MyURL_3t"],
       
"glasdjlasd": ["MyURL_1tp", "MyURL_3tp"]
       
"more......": [ "... unknown number of elements ..." ]
   
}
}

If i have the arrays, I know how to extract the elements one by one as a string:

Call: ElementExtract(MaArray[i], &MyString);

int ElementExtract(bsoncxx::document::element eleDUT, std::string * strStringVal){

 
int iErr = 0;
  strStringVal
->clear();

 
if (! eleDUT) {
    iErr
= 1;   // element searched does not exist
 
} else {
   
// checking if type correct
   
if (eleDUT.type() != bsoncxx::types::b_utf8::type_id) {
      iErr
= 2; // element searched, is found, but has not the right value.
   
}else{
     
// Extract the string  
      strStringVal
->append( eleDUT.get_utf8().value.to_string() );
   
}
 
}

 
return iErr;
}


javantamt

unread,
Jun 4, 2016, 3:11:21 PM6/4/16
to mongodb-user
I've to correct my self. The function can only handle document::element, no array::element.
A document::element is a key & Value and a Array Element is only a value?

javantamt

unread,
Jun 7, 2016, 11:55:09 AM6/7/16
to mongodb-user
SOLVED:
use the force of iterators...

bsoncxx::builder::stream::document MyBuilderTmp = document{};

bsoncxx
::document::value blubb = MyBuilderTmp << "Key1" << "Val1" << "Key2" << "Val2" << finalize;
bsoncxx
::document::view MyBlubbView = blubb.view();

std
::cout << to_json(MyBlubbView) << std::endl;

 
auto size = MyBlubbView.length();
 
auto MyBegin = MyBlubbView.begin();
 
auto MyEnd = MyBlubbView.end();
 
auto num = std::distance(MyBegin,MyEnd);
 
auto Mykey = MyBegin->key();
 
auto Myval = MyBegin->get_utf8().value.to_string();
 
MyBegin++; // it's no more my begin.
 
auto Mykey2 = MyBegin->key();
 
// make shure bevore calling this function that the value is a string indeed.
 
// Otherwise Runtime say's: No no no!
 
auto Myval2 = MyBegin->get_utf8().value.to_string();

 std
::cout
 
<< "\nSize of structure: " << size
 
<<"\nNum Keys: " << num
 
<<"\nMy Keys: " << Mykey
 
<< " val:  " << Myval
 
<< "\nnext Key: " << Mykey2
 
<< " and its value: " << Myval2
 
<< std::endl;

Output:
{
   
"Key1" : "Val1",
   
"Key2" : "Val2"
}

Size of structure: 35
Num Keys: 2
My Keys: Key1 val:  Val1
next Key: Key2 and its value: Val2
Reply all
Reply to author
Forward
0 new messages