mongodb连接池 mongodb连接c

导读:MongoDB是一种文档型数据库,与传统的关系型数据库不同,它使用BSON(二进制JSON)格式来存储数据 。本文将介绍如何在C语言中连接MongoDB,并进行基本的CRUD操作 。
1. 安装MongoDB C驱动程序
首先需要安装MongoDB C驱动程序,可以通过以下命令进行安装:
```
sudo apt-get install libmongoc-dev
2. 连接MongoDB数据库
连接MongoDB数据库需要指定主机名、端口号和数据库名称 , 可以使用以下代码进行连接:
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
bson_error_t error;
const bson_t *doc;
mongoc_init();
client = mongoc_client_new("mongodb://localhost:27017/");
collection = mongoc_client_get_collection(client, "testdb", "testcollection");
cursor = mongoc_collection_find_with_opts(collection, NULL, NULL, NULL);
while (mongoc_cursor_next(cursor, &doc)) {
char *str = bson_as_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}
if (mongoc_cursor_error(cursor, &error)) {
fprintf(stderr, "Cursor Error: %s\n", error.message);
mongoc_cursor_destroy(cursor);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup();
3. 插入数据
插入数据需要先创建一个bson_t对象,然后填充数据,最后调用mongoc_collection_insert_one()方法进行插入 。以下是示例代码:
bson_t *doc;
mongoc_insert_one_opts_t *insert_opts;
doc = bson_new();
BSON_APPEND_UTF8(doc, "name", "John");
BSON_APPEND_INT32(doc, "age", 30);
insert_opts = mongoc_insert_one_opts_new();
if (!mongoc_collection_insert_one(collection, doc, insert_opts, NULL, &error)) {
【mongodb连接池 mongodb连接c】fprintf(stderr, "Insert Failed: %s\n", error.message);
mongoc_insert_one_opts_destroy(insert_opts);
bson_destroy(doc);
4. 更新数据
更新数据需要先创建一个bson_t对象,然后填充查询条件和更新内容,最后调用mongoc_collection_update_one()方法进行更新 。以下是示例代码:
bson_t *query;
bson_t *update;
mongoc_update_one_opts_t *update_opts;
query = BCON_NEW("name", "John");
update = BCON_NEW("$set", "{", "age", BCON_INT32(31), "}");
update_opts = mongoc_update_one_opts_new();
if (!mongoc_collection_update_one(collection, query, update, update_opts, NULL, &error)) {
fprintf(stderr, "Update Failed: %s\n", error.message);
mongoc_update_one_opts_destroy(update_opts);
bson_destroy(query);
bson_destroy(update);
5. 删除数据
删除数据需要先创建一个bson_t对象,然后填充查询条件,最后调用mongoc_collection_delete_one()方法进行删除 。以下是示例代码:
mongoc_delete_one_opts_t *delete_opts;
delete_opts = mongoc_delete_one_opts_new();
if (!mongoc_collection_delete_one(collection, query, delete_opts, NULL, &error)) {
fprintf(stderr, "Delete Failed: %s\n", error.message);
mongoc_delete_one_opts_destroy(delete_opts);
总结:本文介绍了如何在C语言中连接MongoDB,并进行基本的CRUD操作 。通过学习本文 , 读者可以掌握使用MongoDB C驱动程序进行数据库操作的方法 。同时,读者也可以根据自己的需求进行扩展和优化 。

    推荐阅读