1

使用 mongocxx 驱动程序,我需要在 mongodb 中查询某个日期范围内的文档(股票数据)。

考虑以下文档格式:

{
  date : ISODate("2010-01-01T00:00:00Z"),
  open : 12.00,
  high : 13.00,
  low : 11.00,
  close : 12.50,
  volume : 100000
}

假设我每个库存有一个集合,每个集合有数百个这样的文档,每个文档都有不同的日期。

如果用户提供两个日期格式为字符串 (yyyy-mm-dd):

std::string start_date = "2010-01-01";
std::string end_date = "2010-02-05";

如何查询 mongo 以获取日期在“start_date”和“end_date”之间(包括)的所有文件?

注意:我使用的是mongodb 3.2.12,mongocxx驱动版本3.0.2

谢谢,

4

1 回答 1

0

不幸的是,似乎没有办法从具有任意时区的字符串中解析日期。假定所有日期解析都在用户的语言环境中,这意味着您需要提供偏移量才能正确查询存储在数据库中的 UTC 日期。理想情况下,这些可以在用户提供字符串时生成,但这显然取决于您的应用程序的性质。

一旦你有了偏移量和日期字符串,std::get_time就会让你大部分时间到达那里。之后,您只需要将 转换为std::tm可以构造的类型,bsoncxx::types::b_date然后照常查询。这是一些完成这项工作的示例代码:

#include <chrono>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/builder/basic/sub_document.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/types.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>

bsoncxx::types::b_date read_date(const std::string& date,
                                 std::int32_t offset_from_utc) {
    std::tm utc_tm{};
    std::istringstream ss{date};

    // Read time into std::tm.
    ss >> std::get_time(&utc_tm, "%Y-%m-%d");

    // Convert std::tm to std::time_t.
    std::time_t utc_time = std::mktime(&utc_tm);

    // Convert std::time_t std::chrono::systemclock::time_point.
    std::chrono::system_clock::time_point time_point =
        std::chrono::system_clock::from_time_t(utc_time);

    return bsoncxx::types::b_date{time_point +
                                  std::chrono::hours{offset_from_utc}};
}

int main() {
    // User inputs

    std::string start_date = "2010-01-01";
    std::string end_date = "2010-02-05";

    std::int32_t offset_from_utc = -5;

    // Code to execute query

    mongocxx::client client{mongocxx::uri{}};
    mongocxx::collection coll = client["db_name"]["coll_name"];

    bsoncxx::builder::basic::document filter;
    filter.append(bsoncxx::builder::basic::kvp(
        "date", [start_date, end_date,
                 offset_from_utc](bsoncxx::builder::basic::sub_document sd) {
            sd.append(bsoncxx::builder::basic::kvp(
                "$gte", read_date(start_date, offset_from_utc)));
            sd.append(bsoncxx::builder::basic::kvp(
                "$lte", read_date(end_date, offset_from_utc)));
        }));

    for (auto&& result : coll.find(filter.view())) {
        std::cout << bsoncxx::to_json(result) << std::endl;
    }
}
于 2017-02-13T19:33:15.363 回答