1

I have a collection of MongoDB documents that look like this:

{
  ...
  "doc_date": ISODate("2018-03-29T00:00:00.000Z"),
  ...
}

How can I use the C++ (non-legacy) MongoDB API to query for this document given just the date (assuming that the time is always 00:00:00.000)? That is, I would like to do something like:

void my_func(std::string date_to_query) {
  auto result = mongo_collection.find_one(document{} 
     << "doc_date" << date_to_query 
     << finalize);  // This obviously doesn't work
  // ...
}
my_func("2018-03-29");

What's the right query to find a document in Mongo by date given a date string?

acm
  • 12,183
  • 5
  • 39
  • 68
Thomas Johnson
  • 10,776
  • 18
  • 60
  • 98

1 Answers1

0

Given the date as a string, convert it to a std::chrono type representing the beginning of the day, and from that construct two bsoncxx::b_date objects that range over the UNIX time period ranging over that day, then construct a query using $gt and $lt (adjusted as needed for inclusive/exclusive bounds).

For some examples see: Find objects between two dates MongoDB

There is probably also a more clever way to do this with the aggregation framework.

acm
  • 12,183
  • 5
  • 39
  • 68