首页 > 其他分享 >libmongoc库和libbson库的使用

libmongoc库和libbson库的使用

时间:2022-12-08 16:37:03浏览次数:64  
标签:char mongoc collection libbson json 使用 bson NULL libmongoc

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) 释放

标签:char,mongoc,collection,libbson,json,使用,bson,NULL,libmongoc
From: https://www.cnblogs.com/caojun97/p/16965257.html

相关文章

  • chmod -R 777使用.
    chmod修改文件和文件夹读写执行属性1。把hh.c文件修改为可写可读可执行chmod777hh.c要修改某目录下所有的文件属性为可写可读可执行chmod777*.*把文件夹名称与后缀名......
  • Python中12个常用模块的使用教程
    1.time模块importtime*一*#时间戳--》结构化时间--》格式化的字符串时间-----------------------------------------------------------------------------res1=tim......
  • 查看内存 磁盘 cpu个数 IO使用情况
    查看内存:free-h或者cat/proc/meminfo|grepMemTotal查看内存使用情况:free-g查看磁盘:df-hl查看物理CPU内核的个数:cat/proc/cpuinfo|grep“cpucores”|un......
  • 使用ADDCOLUMNS 和 SUMMARIZE的组合
    先说结论,建议不要使用SUMMARIZE函数来增加扩展列,而使用ADDCOLUMNS和SUMMARIZE的组合。虽然SUMMARIZE函数被标记为弃用,但是有时使用起来真的非常方便。ADDCOLUMNS(......
  • 使用chatGPT写一篇关于在线客服系统的博客-在线客服系统:快速解决客户问题的利器
    不想写介绍文案了,让AI帮我写一篇 在线客服系统:快速解决客户问题的利器在线客服系统是一种软件系统,它能够提供即时的在线客服服务。客户可以通过网页、移动应用或其他渠......
  • 使用 archetype-catalog 快速搭建
    在使用IDEA新建一个MavenArchetype的时候ArcheType的可选项并不是很多。我们可以从apachemaven下载一份archetype-catalog来快速搭建想要的项目。1.从https:......
  • SourceGenerator 使用姿势(1):生成代理类,实现简单的AOP
    SourceGenerator已经出来很久了,也一直在关注。之前观摩大佬 xljiulang 的 WebApiClient 使用SourceGenerator生成接口代理类,深受启发,准备拿过来用看看(发出白嫖的声......
  • J-Link使用笔记(二):J-Flash 入门
    介绍J-Flash是J-Link系列工具里用于FLASH操作的GUI工具,也支持命令行方式操作。打开软件配置工程打开后软件界面如下:为了对芯片进行烧写,需要先配置工程:根据实际使......
  • 编程使用系统热键{演示RegisterHotKey()和UnregisterHotKey()}
    PurpleEndurer原创RegisterHotKey()================================函数功能:该函数定义一个系统范围的热键。函数原型:BOOLRegisterHotKey(HWNDhWnd,intid,UINTfsModifie......
  • Ubuntu20.04使用valgrind进程内存分析
     一、安装在官网https://valgrind.org/downloads/上下载软件,目前最新版本是Valgrind3.20.0。然后按照下面的命令解压安装sudoapt-getinstallautomakesudoapt-......