MongoDB中以bson的数据格式存储文档,C驱动程序使用LibsBon创建BSON文档。构建bson文档的主要方式如下:附加关键值对,使用BCON,或解析JSON。
示例:创建如下所示的一个bson文档
{
id: "9239-sakjh-8wej-kshsa",
name : "sample",
age : 22,
address : {
Province : “shanxi”,
city : "xian"
},
degrees : [{ degree: "BA", school : "Vassar" }, { degree: "PhD", school : "Yale" }]
}
1、附加键值对
一个BSON文档,在代码中以bson_t呈现,可以使用Libson的附加函数一次构建一个字段。
void AppendBsonDocument(bson_t* ptDocument)
{
char buf[16];
const char* key;
size_t keylen;
bson_t child;
bson_t child_1;
// id
BSON_APPEND_UTF8(ptDocument, "id", "9239-sakjh-8wej-kshsa");
// name
BSON_APPEND_UTF8(ptDocument, "name", "sample");
// age
BSON_APPEND_INT32(ptDocument, "age", 22);
// address
BSON_APPEND_DOCUMENT_BEGIN(ptDocument, "address", &child);
BSON_APPEND_UTF8(&child, "Province", "shanxi");
BSON_APPEND_UTF8(&child, "city", "xian");
bson_append_document_end(ptDocument, &child);
// degrees
BSON_APPEND_ARRAY_BEGIN(ptDocument, "degrees", &child);
for (i = 0; i < sizeof degrees / sizeof(char *); ++i) {
keylen = bson_uint32_to_string(i, &key, buf, sizeof buf);
BSON_APPEND_DOCUMENT_BEGIN(&child, key, &child_1);
BSON_APPEND_UTF8(&child_1, "degree", degrees[i]);
BSON_APPEND_UTF8(&child_1, "school", schools[i]);
bson_append_document_end(&child, &child_1);
}
bson_append_array_end(ptDocument, &child);
}
2、使用BCON
BSON C对象表示法,简称BCON,是以更接近预期格式构建BSON文档的另一种方式。它的类型安全性低于BSON的追加功能,但导致代码较少。
void CreateBCONDocument(bson_t* ptDocument)
{
ptDocument = BCON_NEW(
"id", BCON_UTF8("9239-sakjh-8wej-kshsa"),
"name", BCON_NEW("sample"),
"age", BCON_INT32(22),
"address", "{",
"Province", BCON_UTF8("shanxi"),
"city", BCON_NEW("xian"),
"}",
"degrees", "[",
"{", "degree", BCON_UTF8("BA"), "school", BCON_UTF8("Vassar"), "}",
"{", "degree", BCON_UTF8("PhD"), "school", BCON_UTF8("Yale"), "}",
"]");
}
3、解析JSON
对bson文档,也可以通过 bson_new_from_json接口获取json字符串来创建。
void CreateBCONFromJson(bson_t* ptDocument)
{
bson_t* bson = NULL;
bson_error_t error;
const char* json = "{\"id\":\"9239-sakjh-8wej-kshsa\", \"name\":\"sample\",\"age\":22}";
bson = bson_new_from_json((const uint8_t *)json, -1, &error);
}