Search code examples
mongodbserializationmongo-cxx-driver

Faster way to get data out of mongo results than field-by-field?


Is there a faster way to parse mongo results back into datastructures than doing it field-by-field as below? I'm currently doing this and it's very slow.

mongocxx::cursor cursor = m_coll.find(<some-query>);
for (bsoncxx::document::view doc : cursor)
{
    RecreatedObj readback;
    readback.Area = doc["Area"].get_int32();
    readback.fieldOne = doc["fieldOne"].get_double();
    readback.fieldTwo = doc["fieldTwo"].get_double();
    readback.fieldThree = doc["fieldThree"].get_int32();
    ...
}

Solution

  • Field lookup is O(N), so you've unwittingly written an O(N^2) algorithm.

    A faster way would be to iterate over the fields in the document view and do your assignments in a switch/case on field name.