1、初始化mongoc
非线程安全,只需调用一次
static
void log_handler (mongoc_log_level_t log_level,
const
char* log_domain,
const
char* message,
void* user_data)
{
cout << "[mongo][" << log_domain << "]" << message;
}
mongoc_log_set_handler (log_handler, NULL);
3、连接mongodb
const
char *uristr = "mongodb://127.0.0.1/";
mongoc_client_t* m_pClient = mongoc_client_new(uristr);
4、获取collection
mongoc_collection_t * m_pCollection = mongoc_client_get_collection(m_pClient, "test_db", "test_collection");
5、打印bson调试
MongoDB使用了BSON这种结构来存储数据和网络数据交换。 mongoc提供了方法将bson格式转化为json, 可以用于打印调试 。
char* str = bson_as_json(doc, NULL);
fprintf(stdout, "%s\n", str);
6、插入记录
bson_error_t error;
bson_t *doc = bson_new();
BSON_APPEND_INT64(doc, "id", 1);
BSON_APPEND_INT64(doc, "field1", 0);
string msg = "test message";
BSON_APPEND_BINARY(doc, "field2", BSON_SUBTYPE_BINARY, (
const uint8_t*)(msg.c_str()), (uint32_t)(msg.size()));
bool r = mongoc_collection_insert(m_pCollection, MONGOC_INSERT_NONE, doc, NULL, &error);
if (!r)
{
cout << "Insert Failure:" << error.message;
}
bson_destroy(doc);
7、更新记录
bson_error_t error;
bson_t *doc = bson_new();
bson_t child;
bson_append_document_begin(doc, "$set", -1, &child);
BSON_APPEND_INT64(&child, "field1", 22);
bson_append_document_end(doc, &child);
bson_t query;
bson_init(&query);
BSON_APPEND_INT64(&query, "id", 1);
bool r = mongoc_collection_update(m_pCollection,
MONGOC_UPDATE_NONE,
&query,
doc,
NULL,
&error);
if (!r)
{
cout << "Update Failure: " << error.message;
}
bson_destroy(&query);
bson_destroy(doc);
8、删除记录
bson_error_t error;
bson_t query;
bson_init(&query);
BSON_APPEND_INT64(&query, "id", 1);
bool r = mongoc_collection_delete(m_pCollection,
MONGOC_DELETE_NONE,
&query,
NULL,
&error);
if (!r)
{
cout << "Delete Failure: " << error.message;
ret = ERR_MONGODB_FAILED;
}
bson_destroy(&query);