How to save mongodb array into vector using c++ driver?
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 valuesp.getObjectField("arr").Vals(ints); // asserts on non int values
or
// this way is more common and does the conversion between numeric typesvector<int> v;BSONObjIterator fields (p.getObjectField("arr"));while(fields.more()) { v.push_back(fields.next().numberInt());}//same as above but using BSONForEach macroBSONForEach(e, p.getObjectField("arr")) { v.push_back(e.numberInt());}
Alternatively, you could just leave the output as a vector<BSONElement>
and use them directly, but then you will need to be sure that the BSONObj will outlive the vector.