MongoDB 使用数组中的 OR 条件构建查询

MongoDB building query with OR condition from an array

本文关键字:OR 条件 构建 查询 数组 MongoDB      更新时间:2023-10-16

我想使用具有以下条件的MongoDB C++api创建和运行查询:

  1. 时间戳在范围内 AND
  2. 从字符串数组中,至少其中一个等于类型

我的MongoDB文档中有这些字段:id_、时间戳、类型

我使用构建器流来创建我的查询。对于过滤时间戳的第一个条件,我做了:

Document doc_timestamp;
doc_timestamp << "timestamp" << open_document <<
"$gt" << startTS <<
"$lte" << endTS
<< close_document

如果我单独运行第一个条件,它会完美运行。但我不确定如何为类型字段执行此操作。我确实喜欢这个:

Document doc_type;
auto arr_type = doc_type <<
"$or" << open_array;
for (auto nNum : nTypes) {
arr_type = arr_type << "type" << std::to_string(nNum);
}
arr_type << close_array;

此筛选器不起作用。它会引发运行时错误。我在这里做错了什么?另外,我如何连接这两个过滤器并向其传递查找函数以运行查询。

提前感谢!

不确定$or是否是数组过滤器的最佳选择。如果要查找数组中是否存在元素,可以使用$in运算符

有一些关于在循环中构建 bson 数组的讨论,就像您尝试的那样,但即使是@acm也建议使用bsoncxx::builder::basic而不是bsoncxx::builder::stream. 使用bsoncxx::builder::basic::array{}可以将所有类型追加到数组中,并通过$in运算符直接在查询中使用它。

关于如何连接两个过滤器,可以一个接一个地添加它们:

using namespace bsoncxx::builder::stream;
// Some random start/end time and types
std::chrono::system_clock::time_point from_time = std::chrono::system_clock::now() - std::chrono::hours(5);
std::chrono::system_clock::time_point to_time = std::chrono::system_clock::now() + std::chrono::hours(5);
const auto types = { "xls", "docx", "pdf" };
auto array_builder = bsoncxx::builder::basic::array{};
for (const auto& type : types ) { array_builder.append(type); }
mongocxx::cursor cursor = db["query"].find(
document{} <<
"timestamp" << open_document <<
"$gt" << bsoncxx::types::b_date{ from_time } <<
"$lt" << bsoncxx::types::b_date{ to_time } <<
close_document <<
"type"      << open_document  <<
"$in" << array_builder <<
close_document <<
finalize
);
for (auto doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}