How to save mongodb array to vector using C ++ driver?

For example, if I do this in a shell

> db.numbers.save( { name: "fibonacci", arr: [0, 1, 1, 2, 3, 5, 8, 13, 21] } )

Then I want to get arrin my C ++ program.

After I got BSONObj, I can get namewith

std::string name = p.getStringField("name");

where pis the BSON object.

But what is the correct way to get elements from an array and store them in std :: vector?

EDIT:

After some research, I found the BSONElement doxygen documentation and did it.

std::vector<int> arr;
std::vector<BSONElement> v = p.getField("arr").Array();
for(std::vector<BSONElement>::iterator it = v.begin(); it != v.end(); ++it)
    arr.push_back(it->numberInt());

But I'm still not sure if this is the right way.

+5
source share
1 answer

Two other ways:

// this way is easy but requires exact type match (no int64->int32 conversion)
std::vector<int> ints;
p.getObjectField("arr").vals(ints); // skips non int values
p.getObjectField("arr").Vals(ints); // asserts on non int values

or

// this way is more common and does the conversion between numeric types
vector<int> v;
BSONObjIterator fields (p.getObjectField("arr"));
while(fields.more()) {
    v.push_back(fields.next().numberInt());
}

//same as above but using BSONForEach macro
BSONForEach(e, p.getObjectField("arr")) {
    v.push_back(e.numberInt());
}

Alternatively, you can simply leave the output as you vector<BSONElement>use them directly, but then you will need to make sure that BSONObj survives the vector.

+6
source

All Articles