MongoDB 使用数组中的 OR 条件构建查询
MongoDB building query with OR condition from an array
我想使用具有以下条件的MongoDB C++api创建和运行查询:
- 时间戳在范围内 AND
- 从字符串数组中,至少其中一个等于类型
我的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;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- MongoDB 使用数组中的 OR 条件构建查询
- C++ if 语句将条件设置为 true 和循环中的 OR-ing 条件之间的行为差异
- 带有逻辑 OR 运算符的 if 条件的缩写?
- 虽然具有多个 OR 条件的循环不退出循环
- C++中的堆栈:切换"or"条件时出现运行时错误
- 如何处理 IF 中的多个 OR 条件
- 如果带有 OR 检查所有条件,则为条件
- 为什么我的 OR 条件检查匹配项的字符串总是返回 true
- C++:for 循环中的多个退出条件(多个变量):AND -ed 或 OR -ed
- if语句在有两个OR选项的第三个条件下不起作用
- 在or条件语句中是否存在强制对两个表达式求值的模式或技巧?
- IF语句中的多个OR或AND条件
- c++中的Enum和OR条件
- gcc 或其他编译器在条件表达式中使用时是否会自动将按位 or 转换为布尔值 or?