随笔 - 79  文章 - 58  trackbacks - 0
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(9)

随笔分类

随笔档案

文章档案

相册

搜索

  •  

积分与排名

  • 积分 - 291746
  • 排名 - 87

最新评论

阅读排行榜

评论排行榜

1、初始化mongoc

非线程安全,只需调用一次
mongoc_init();

2、设置日志回调

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);
posted on 2014-09-26 17:03 merlinfang 阅读(8318) 评论(0)  编辑 收藏 引用 所属分类: mongodb

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理