Loading

MongoDB:JSON和BSON

一、BSON

在MongoDB中数据的存储格式是:BSON,这是一种二进制格式的JSON变种。

MongoDB中操作数据也是基于BSON,涉及的函数库:libbson.h

二、JSON和BSON的转换

🔸 JSON转换成BSON

单步拼接方式:

#include <mongoc/mongoc.h>
#include <bson/bson.h>

int main(int argc, char *argv[])
{
    bson_t *query= NULL;
    char *str = NULL;
    query = BCON_NEW (
                    "name", BCON_UTF8("ZhangSan"),
                    "age", BCON_INT32 (19),
    		    "timestamp_string", BCON_REGEX("^2022-11-09","i")
    		    );
    str = bson_as_json(query, NULL);
    printf("%s\n",str);
    bson_free(str);
    bson_destroy(query);
    return 0;
} 

运行结果:

整体转换方式:

#include <mongoc/mongoc.h>
#include <bson/bson.h>

int main(int argc, char *argv[])
{
	bson_t *query = NULL;
	bson_error_t error;
	char *str = NULL;
	char message[100] = {0};
	char json[100] = {"{\"name\":\"ZhangSan\",\"age\":19,\"sex\":\"male\"}"};
	if (!(query = bson_new_from_json((unsigned char *)json, -1, &error)))
	{
		printf("%s\n", error.message);
	}
	else
	{
		str = bson_as_json(query, NULL);
		printf("%s\n", str);
		bson_free(str);
	}
	bson_destroy(query);
        return 0;
} 

运行结果;

🔸 BSON转换成JSON

  char *str = NULL;
  bson_t *query = NULL;
  str = bson_as_json(query, NULL); // 该函数进行转换
  printf("%s\n", str);
  bson_free(str);
posted @ 2023-02-03 09:55  eiSouthBoy  阅读(529)  评论(0)    收藏  举报