mongodb:在日期范围内查询
问题描述:
使用mongocxx驱动程序,我需要查询mongodb查找属于某个日期范围内的文档(库存数据)。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";
我如何查询蒙戈得到与“起始日期”和“END_DATE”的日期的所有文件(包括的)?
注:我使用MongoDB的3.2.12,mongocxx驱动程序版本3.0.2
感谢,
答
遗憾的是,似乎没有要解析来自任意时区的字符串日期的方法;假设所有日期解析都在用户的语言环境中,这意味着您需要提供一个偏移以便能够正确查询存储在数据库中的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;
}
}
自从我张贴的问题的时候,我发现了[这](http://stackoverflow.com/questions/21021388/how-to-parse-a- date-string-into-a-c11-stdchrono-time-point-or-similar)的帖子,这有助于第一部分。然而,我的查询不起作用,因为我没有考虑UTC时间,所以谢谢指出! – tmalt