MongoDB C driver: how to use regex query collection?

问题内容:

for example, In MySQL the query like this:

select name from test_tab where id = 1 and  name like 'test%'; 

I want to translate this query in mongodb by mongodb C driver, so I write the code like this, but all don’t work(the searchDoc() function is okay.

string strName = "";
bson_t *cond = bson_new();
BSON_APPEND_INT32(cond, "id", 1);
if (strlen(name.c_str()) > 0)
{
    strName = "/^" + name + "/";
    bson_t *child;
    child = bson_new();
    bson_append_document_begin(cond, "name", -1, child);
    BSON_APPEND_UTF8(child, "$regex", strName.c_str());
    bson_append_document_end(cond, child);
}
mongoc_cursor_t *cursor(NULL);
int iRet = searchDoc("db", "test_tab", cond, cursor);
if (iRet < 0)
{
    bson_destroy(cond);
    mongoc_cursor_destroy(cursor);
    return -1;
}

and

string strName = "";
bson_t *cond = bson_new();
BSON_APPEND_INT32(cond, "id", 1);
if (strlen(name.c_str()) > 0)
{
    strName = "/^" + name + ".*/";
    BSON_APPEND_REGEX(cond, "name", strName.c_str(), "i");
}
mongoc_cursor_t *cursor(NULL);
int iRet = searchDoc("db", "test_tab", cond, cursor);
if (iRet < 0)
{
    bson_destroy(cond);
    mongoc_cursor_destroy(cursor);
    return -1;
}

How can I build the regex pattern to query record work okay?
Thank you

问题评论:

答案:

答案1:

I seach this page: https://jira.mongodb.org/browse/CDRIVER-206,
there is a important tips: “You do not need to include the forward-slash when building a regex.”

so I delete the forward-slash, my code

 strName = "/^" + name + ".*/"; 
 BSON_APPEND_REGEX(cond, "name", strName.c_str(), "i");

change to

  strName = "/^" + name + ".*/";
  BSON_APPEND_REGEX(cond, "name", strName.c_str(), "i");

It can work. My problem has been solved.

答案评论:

原文地址:

https://stackoverflow.com/questions/47746057/mongodb-c-driver-how-to-use-regex-query-collection

Add a Comment