MongoDB中Bson文件的建立
MongoDB中儲存Bson文件的方式
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);
}