最近一个项目,使用了MongoDB,c 语言调用 mongo-c-driver 函数实现数据库的操作,网上资料较少,自己摸索总结了一些方法,做个记录。
一、查询
1、函数 mongoc_collection_find_with_opts 和 mongoc_collection_find
如果只有查询条件,没有输出条件,这两个函数都可使用;如果有输出条件,则使用mongoc_collection_find_with_opts,结合关键字:projection
例子:
query = BCON_NEW("AfileID", FileID);
bson_init(&child3);
BSON_APPEND_DOCUMENT_BEGIN(&child3, "projection", &child);
BSON_APPEND_INT32(&child, "_id", 0);
BSON_APPEND_INT32(&child, "username", 0);
bson_append_document_end(&child3, &child);
cursor = mongoc_collection_find_with_opts(collection_file, query, &child3, NULL);
其中,_id是MongoDB自动添加的id字段, BSON_APPEND_INT32(&child, "_id", 0);中的0,表示不输出。
2、比较
1)不等于:not eq:
bson_append_document_begin(&child2, "username", -1, &child3);
bson_append_document_begin(&child3, "$not", -1, &child4);
BSON_APPEND_UTF8(&child4, "$eq", m_username);
bson_append_document_end(&child3, &child4);
bson_append_document_end(&child2, &child3);
2)包含:regex (任意位置开始匹配)
bson_append_document_begin(&child2, "userpart", -1, &child3);
BSON_APPEND_UTF8(&child3, "$regex", sstr2.c_str());
bson_append_document_end(&child2, &child3);
regex ^ (从头开始匹配)