libmongoc库和libbson库的使用
学习一项知识,最好的方式是查看官方说明书。
测试环境:
操作系统:Windows 10 x64
MongoDB版本:mongodb-5.0.14
MongoDB Client Library版本:libmongoc 1.23.1
前言
工作和学习过程中,需要用到数据库,这里挑选了MongoDB 非关系型数据库。使用数据库,肯定离不开数据库的 增、删、改、查。
MongoDB自带了客户端程序:mongosh.exe
,基本可以满足用户所有的操作需要。但是进行程序二次开发,我们还是需要使用 MongoDB Client Library.
本文主要介绍 libmongoc库 和 libbson库的常用函数,以及使用过程中的注意事项
一、libmongoc库和libbson库的介绍
官网介绍:
A Cross Platform MongoDB Client Library for C
The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages.
It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.
MongoDB的数据存储格式:bson ,那么就需要libbson库。
数据库原始数据:
{"id":1001,"name":"ZhangSan","age":18,"sex":"male","Chinese":93.0,"Math":100.0,"English":80.0}
{"id":1002,"name":"LiSi","age":18,"sex":"male","Chinese":100.0,"Math":60.0,"English":80.0}
{"id":1003,"name":"WangWu","age":19,"sex":"male","Chinese":90.0,"Math":100.0,"English":90.0}
{"id":1004,"name":"ZhaoLiu","age":19,"sex":"male","Chinese":95.0,"Math":70.0,"English":80.0}
{"id":1005,"name":"XiaoLi","age":18,"sex":"female","Chinese":100.0,"Math":100.0,"English":80.0}
二、libmongoc库的使用
数据库的CRUD(即create、read、update、delete)操作
2-1 create(增操作)
以json格式传入,在表中创建一条bson。
实现代码
#include <mongoc/mongoc.h>
static int lib_collection_create_document(const char *uri_string, const char *database_name, const char *collection_name, const char *json)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
bson_error_t error;
bson_oid_t oid;
bson_t *doc = NULL;
bson_t *json_d = NULL;
int result = 0;
/* create mongoc client instace */
client = mongoc_client_new(uri_string);
/* create collection instace */
collection = mongoc_client_get_collection(client, database_name, collection_name);
/* create bson instace */
doc = bson_new();
/* init bson oid.
* oid is primary key in collection
*/
bson_oid_init(&oid, NULL);
/* bson oid append bson_t */
BSON_APPEND_OID(doc, "_id", &oid);
json_d = bson_new_from_json((unsigned char *)json, -1, &error);
if (!json_d)
{
fprintf(stderr, "%s\n", error.message);
result = -1;
}
bson_concat(doc, json_d);
bson_destroy(json_d);
if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error))
{
fprintf(stderr, "%s\n", error.message);
result = -2;
}
/* free bson_t memory */
bson_destroy(doc);
/* free mongoc_collection_t */
mongoc_collection_destroy(collection);
/* free mongoc_client_t */
mongoc_client_destroy(client);
return result;
}
int main(int argc, char *argv[])
{
mongoc_init();
const char *uri_string = "mongodb://10.8.198.55:27017";
const char *database = "event_database";
const char *collection = "student_coll";
// add a json to collection
char json[500] = {"{\"id\":1006,\"name\":\"XiaoHong\",\"age\":24,\"sex\":\"female\",\"Chinese\":74.0,\"Math\":85.0,\"English\":81.0}"};
if (0 == lib_collection_create_document(uri_string, database, collection, json))
{
printf("Create successful : %s\n", json);
}
mongoc_cleanup();
return 0;
}
运行结果:
2-2 read(查操作)
在表中查找符合条件的document,通过数组返回
实现代码:
#include <mongoc/mongoc.h>
static int lib_collection_read_document(const char *uri_string, const char *database_name, const char *collection_name, const char *json_opts,
char doc_list_arr[][300], int *num_of_docs)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
mongoc_cursor_t *cursor = NULL;
bson_error_t error;
const bson_t *doc = NULL;
bson_t *query = NULL;
bson_t *json_d = NULL;
char *str = NULL;
int result = 0;
client = mongoc_client_new(uri_string);
collection = mongoc_client_get_collection(client, database_name, collection_name);
query = bson_new();
json_d = bson_new_from_json((unsigned char *)json_opts, -1, &error);
if (!json_d)
{
fprintf(stderr, "%s\n", error.message);
result = -1;
}
bson_concat(query, json_d);
bson_destroy(json_d);
cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);
while (mongoc_cursor_next(cursor, &doc))
{
//str = bson_as_canonical_extended_json(doc, NULL);
//str = bson_as_relaxed_extended_json(doc, NULL);
str = bson_as_json(doc, NULL);
sprintf(doc_list_arr[*num_of_docs], "%s", str);
(*num_of_docs)++;
bson_free(str);
}
bson_destroy(query);
mongoc_cursor_destroy(cursor);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
return result;
}
int main(int argc, char *argv[])
{
mongoc_init();
const char *uri_string = "mongodb://10.8.198.55:27017";
const char *database = "event_database";
const char *collection = "student_coll";
/* read jsons from collection with options */
char json_opts[300] = {"{\"age\":18,\"sex\":\"male\"}"};
char doc_list_arr[100][300] = {0};
int num_of_docs = 0;
lib_collection_read_document(uri_string, database, collection, json_opts, doc_list_arr, &num_of_docs);
for (int i = 0; i < num_of_docs; i++)
{
printf("%s\n", doc_list_arr[i]);
}
mongoc_cleanup();
return 0;
}
运行结果:
2-3 update(改操作)
在表中查找指定的json,符合条件的json进行修改
注意:这里修改值的类型为string
实现代码:
#include <mongoc/mongoc.h>
#include <bson/bson.h>
static int lib_collection_update_document(const char *uri_string, const char *database_name, const char *collection_name, const char *json_opts,
const char *key, const char *value_string)
{
mongoc_collection_t *collection = NULL;
mongoc_client_t *client = NULL;
bson_error_t error;
mongoc_cursor_t *cursor = NULL;
const bson_t *doc = NULL;
bson_t *update = NULL;
bson_t *query = NULL;
int result = 0;
client = mongoc_client_new(uri_string);
collection = mongoc_client_get_collection(client, database_name, collection_name);
update = BCON_NEW("$set",
"{",
key,
BCON_UTF8(value_string),
"}");
query = bson_new_from_json((unsigned char *)json_opts, -1, &error);
if (!query)
{
fprintf(stderr, "%s\n", error.message);
result = -1;
}
cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);
while (mongoc_cursor_next(cursor, &doc))
{
if (!mongoc_collection_update_one(collection, doc, update, NULL, NULL, &error))
{
fprintf(stderr, "%s\n", error.message);
result = -2;
break;
}
}
bson_destroy(query);
bson_destroy(update);
mongoc_cursor_destroy(cursor);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
return result;
}
int main(int argc, char *argv[])
{
mongoc_init();
const char *uri_string = "mongodb://10.8.198.55:27017";
const char *database = "event_database";
const char *collection = "student_coll";
/* update documents from collection wiht options */
char json_opts[300] = { "{\"id\":1006}" };
const char *key = "name";
const char *value = "XiaoHe";
if (0 == lib_collection_update_document(uri_string, database, collection, json_opts, key, value))
{
printf("Update successful\n");
}
mongoc_cleanup();
return 0;
}
运行结果:
2-4 delete(删操作)
在表中查找指定的json,符合条件的json进行删除
实现代码:
#include <mongoc/mongoc.h>
#include <bson/bson.h>
static int lib_collection_delete_document(const char *uri_string, const char *database_name, const char *collection_name, const char *json_opts)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
mongoc_cursor_t *cursor = NULL;
bson_error_t error;
const bson_t *doc = NULL;
bson_t *query = NULL;
int result = 0;
client = mongoc_client_new(uri_string);
collection = mongoc_client_get_collection(client, database_name, collection_name);
query = bson_new_from_json((unsigned char *)json_opts, -1, &error);
if (!query)
{
fprintf(stderr, "%s\n", error.message);
result = -1;
}
cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);
while (mongoc_cursor_next(cursor, &doc))
{
if (!mongoc_collection_delete_one(collection, doc, NULL, NULL, &error))
{
fprintf(stderr, "%s\n", error.message);
result = -2;
}
}
bson_destroy(query);
mongoc_cursor_destroy(cursor);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
return result;
}
int main(int argc, char *argv[])
{
mongoc_init();
const char *uri_string = "mongodb://10.8.198.55:27017";
const char *database = "event_database";
const char *collection = "student_coll";
/* delete documents with options in collection */
char json_opts[300] = { "{\"age\":19}" };
if (0 == lib_collection_delete_document(uri_string, database, collection, json_opts))
{
printf("Delete successful\n");
}
mongoc_cleanup();
return 0;
}
运行结果:
三、libbson库的使用
-
将bson格式转换成json格式(value不带类型)
函数:char * bson_as_json (const bson_t *bson, size_t *length);
输出格式:
注意事项:函数返回值(指针)记得使用函数
void bson_free (void *mem)
释放 -
将bson格式转换成json格式(value带类型)
函数:char * bson_as_canonical_extended_json (const bson_t *bson, size_t *length)
输出格式:
注意事项:函数返回值(指针)记得使用函数
void bson_free (void *mem)
释放