以下是我正在尝试使用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: /./ }" }
然后在文档{}中传递vReg,如顶部代码所示
document{} << "Vehicle_Registration" << vReg
此处vReg以字符串"{ $regex: /./ }"
(带引号)而不是{ $regex: /./ }
(不带引号)传递。因此,它被视为一个字符串,而不是在查询中作为正则表达式进行评估,因此没有搜索结果。
有人可以帮我知道如何将其作为正则表达式传递吗?
谢谢!
答案 0 :(得分:2)
您需要将正则表达式子句设为适当的BSON子文档,而不是字符串。幸运的是,bsoncxx::types::b_regex
类型有一个快捷方式,当添加到BSON文档时会扩展到子文档。
已更新:要了解如何切换您描述的方式,以下是使用三元运算符然后将查询字符串或正则表达式包装在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)
答案 1 :(得分:0)
如xdg's answer指出的那样,只需添加另一个由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/
。