gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:03:02 25 4
gpt4 key购买 nike

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

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

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

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

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

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

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;

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

提前致谢!

最佳答案

不确定 $ 或 是否是数组过滤器的最佳选择。如果您想查找某个元素是否存在于数组中,您可以使用 $in operator

已经有some discussions about building a bson array in a loop就像您的尝试一样,但即使是 @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;
}

关于c++ - MongoDB 使用数组中的 OR 条件构建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59194451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com