3

以下是我尝试使用 mongocxx 驱动程序查询 mongodb 的一段代码。

/*查找所有匹配过滤器的代码*/

mongocxx::cursor cursor = collection.find(
    document{} << "Vehicle_Registration" << vReg
    << "Vehicle_Make" << vMake
    << "Vehicle_Model" << vModel 
    << "Vehicle_Owner" << vOwner 
    << finalize);

这里

Vehicle_Registration、Vehicle_Make、Vehicle_Model、Vehicle_Owner

是集合的字段。

的价值

vReg、vMake、vModel、vOwner

由用户在屏幕上指定。如果用户只指定了这些值中的一部分(不是全部),则其余值保持为 NULL。为了避免搜索 NULL 值,我尝试将它们设置为正则表达式 { $regex: /./ } 以便 NULL 值不会影响搜索。

此正则表达式适用于 mongo shell,设置为此正则表达式的所有字段都将被忽略并且不影响搜索。

但是在代码中,要设置这个正则表达式,我会这样做:

If (vReg == NULL) {  vreg = "{ $regex: /./ }"  }

然后在 document{} 中传递 vReg,如顶部代码所示

document{} << "Vehicle_Registration" << vReg

这里 vReg 作为字符串"{ $regex: /./ }"(带引号)而不是{ $regex: /./ }(不带引号)传递。因此,它被认为是一个字符串,而不是在查询中作为正则表达式进行评估,因此没有搜索结果。

有人可以帮我知道如何将它作为正则表达式传递吗?

谢谢!

4

2 回答 2

3

您需要使正则表达式子句成为正确的 BSON 子文档,而不是字符串。幸运的是,有一个使用该bsoncxx::types::b_regex类型的快捷方式,当添加到 BSON 文档时,它会扩展为子文档。

更新:要查看如何切换描述的方式,这里有一个示例,它使用三元运算符,然后将查询字符串或正则表达式包装在 a 中bsoncxx::types::value,这是一个联合类型:

using namespace bsoncxx::builder::stream;
using namespace bsoncxx::types;

int main() {
    auto inst = mongocxx::instance{};
    auto client = mongocxx::client{mongocxx::uri{}};
    auto coll = client["test"]["regex_question"];
    coll.drop();

    std::string vModel;
    auto empty_regex = b_regex(".", "");

    coll.insert_one(document{} << "Vehicle_Make"
                               << "Toyota"
                               << "Vehicle_Model"
                               << "Highlander" << finalize);

    auto filter = document{} << "Vehicle_Make"
                             << "Toyota"
                             << "Vehicle_Model"
                             << (vModel.empty() ? value{empty_regex} : value{b_utf8{vModel}})
                             << finalize;

    std::cout << bsoncxx::to_json(filter) << std::endl;

    std::cout << "Found " << coll.count(filter.view()) << " document(s)" << std::endl;
}

这给出了这个输出:

{ "Vehicle_Make" : "Toyota", "Vehicle_Model" : { "$regex" : ".", "$options" : "" } }
Found 1 document(s)
于 2016-12-12T15:38:00.960 回答
0

正如xdg的回答所指出的那样,只需添加另一个不区分大小写的查找示例:b_regex

collection.find(
    bsoncxx::builder::stream::document{} 
        << KEY_VALUE 
        << open_document 
        << "$regex"
        << bsoncxx::types::value{bsoncxx::types::b_regex{"^" + tag, "i"}}
        << close_document 
        << finalize
);

MongoDB 手册说应该是,这让我很恼火,但实际上这里不需要{ <field>: { $regex: /pattern/, $options: '<options>' } }斜线//pattern/

于 2021-04-17T05:05:16.330 回答