Search code examples
c++mongodbc++11bsonmongo-cxx-driver

BSON types and std::chrono


In attempting to work through the official MongoDB C++ tutorial, I've run into an error I don't understand. The following code is pulled right from their website:

#include <chrono>

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;

int main()
{
//...
    bsoncxx::document::value restaurant_doc = document{}
        << "address" << open_document << "street"
//...
        << bsoncxx::types::b_date{std::chrono::milliseconds{12323}}
//...
        << "restaurant_id" << "41704620"
        << finalize;

And the errors I get from GCC (v6.1.1) look like:

insert.cpp: In function ‘int main()’:
insert.cpp:36:65: error: no matching function for call to     ‘bsoncxx::v_noabi::types::b_date::b_date(<brace-enclosed initializer list>)’
   << bsoncxx::types::b_date{std::chrono::milliseconds{12323}}

In file included from /usr/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:26:0,
                 from /usr/include/bsoncxx/v_noabi/bsoncxx/builder/stream/document.hpp:17,
                 from insert.cpp:3:
/usr/include/bsoncxx/v_noabi/bsoncxx/types.hpp:306:14: note: candidate: bsoncxx::v_noabi::types::b_date::b_date(const time_point&)
     explicit b_date(const std::chrono::system_clock::time_point& tp)
              ^~~~~~

I tried initializing the chrono::milliseconds with parens instead of braces, but then GCC just complained more clearly about the type mismatch between the available bsoncxx::types::b_date constructors and what I was providing it. I also tried feeding it a chrono::system_clock::time_point initialized with that same number, per the MongoDB C++11 Driver docs, but I still got a mismatch.

So... I'm not sure why the tutorial material doesn't work for me, nor do I fully understand the typing, templating, or brace initializer lists of C++. And while I'd be happy to go through a tutorial specific to the issue I'm having, I'm not even sure what to Google for. Knowledge gaps are too broad. =P

Consequently, any help would be greatly appreciated. =)


Solution

  • Something like

    bsoncxx::types::b_date { std::chrono::system_clock::time_point {
        std::chrono::milliseconds { 12323 } } }
    

    or

    bsoncxx::types::b_date { std::chrono::system_clock::now() +
        std::chrono::milliseconds { 12323 } }
    

    should hopefully work. (The first will be relative to the system clock's epoch, which is probably the Unix epoch Jan 1, 1970 00:00:00 UTC on Linux systems.)