有兩種方法。 月1日,你可以將其轉換爲BSON,並提取值的鍵「1」,「2」等:
bson_t * doc = /*your bson doc*/;
bson_iter_t iter;
bson_iter_init(&iter, doc);
// requesting for f
bson_iter_find(&iter, "f");
const ui8 * data = NULL;
uint32_t len = 0;
bson_iter_array(&iter, &len, &data);
bson_t * fSubArray = bson_new_from_data(data, len);
bson_iter_t fIter;
bson_iter_init(&fIter, fSubArray);
bson_iter_find(&fIter, "0");
bson_iter_int32(&fIter) == 283;
bson_iter_find(&fIter, "1");
bson_iter_int32(&fIter) == 180;
bson_iter_find(&fIter, "2");
bson_iter_int32(&fIter) == 284;
// requesting for l
bson_iter_find(&iter, "l");
const ui8 * data = NULL;
uint32_t len = 0;
bson_iter_array(&iter, &len, &data);
bson_t * fSubArray = bson_new_from_data(data, len);
bson_iter_t fIter;
bson_iter_init(&fIter, fSubArray);
bson_iter_find(&fIter, "0");
strcmp(bson_iter_utf8(&fIter), "1") == 0;
bson_iter_find(&fIter, "1");
strcmp(bson_iter_utf8(&fIter), "29") == 0;
此外,mongoc推薦使用bson_uint32_to_string功能快速字符串爲int轉換。
第二可以直接查看在bson_iter_array數據(& ITER,& LEN,&數據)時,如果第一方法的性能比較不明確:
數據具有下一格式:
total bytes in data | bson type | string index | 4 for int32, 1 for char, etc.| bson type | ... | end of data
4 bytes | 1 byte | null-terminated string | sizeof(element) bytes | 1 byte | ... | \0
所以,如果你知道你的數據的大小,你可以直接訪問它。但你應該考慮,數據有淨字節順序。
例如,如果我們知道,這是陣列[INT32(2),Int64的(4)],數據將是:
4 bytes | 1 byte | null-terminated string | sizeof(int32) bytes | 1 byte | 1 byte | sizeof(int64) bytes | \0
23 0 0 0 | 16 | 48 0 | 2 0 0 0 | 18 | 49 0 | 4 0 0 0 0 0 0 0 | 0
totaly 23 bytes | BSON_TYPE_INT32 | "0\0" | 2 | BSON_TYPE_INT64 | "1\0" | 4 | end