Docs 菜单
Docs 主页
/ /

BSON

在本指南中,您可以学习;了解如何使用C驾驶员创建BSON文档、写入BSON文档写入文件以及从文件读取BSON数据。

BSON 或二进制 JSON 是 MongoDB 用来组织和存储数据的数据格式。这种数据格式包括所有 JSON 数据结构类型,并增加了对日期、不同大小的整数、ObjectId 和二进制数据等类型的支持。有关支持类型的完整列表,请参阅 BSON 类型服务器手册页面。

您可以通过包含 libbson包在C应用程序中使用BSON文档。

本指南中的代码示例使用以下 BSON 文档作为示例:

{
"address" : {
"street" : "Pizza St",
"zipcode" : "10003"
},
"coord" : [-73.982419, 41.579505]
"cuisine" : "Pizza",
"name" : "Mongo's Pizza"
}

BSON文档由C驾驶员中的 bson_t 类型表示。您可以使用 BCON_NEW() 函数创建 bson_t实例。以下示例创建示例BSON文档的 bson_t 表示形式:

bson_t *doc = BCON_NEW( "address", "{",
"street", BCON_UTF8("Pizza St"),
"zipcode", BCON_UTF8("10003"), "}",
"coord", "[", BCON_DOUBLE(-73.982419), BCON_DOUBLE(41.579505), "]",
"cuisine", BCON_UTF8("Pizza"),
"name", BCON_UTF8("Mongo's Pizza")
);

注意

BSON字段值

在BSON文档中创建或附加字段时,请确保使用适当的BCON_* 函数来正确表示字段值。有关BCON_* 函数的完整列表,请参阅C驾驶员GitHub存储库中的 bson-bcon.h文件。

您可以使用 BCON_APPEND() 函数将字段值对追加到现有的 bson_t实例。以下示例将新的 yearEstablished字段和值附加到示例BSON文档:

BCON_APPEND(doc, "yearEstablished", BCON_INT32(1996));

您还可以使用与要附加值的数据类型相对应的 bson_append_* 函数。以下示例使用 bson_append_int32() 函数添加与前面的示例相同的字段值对:

bson_append_int32(doc, "yearEstablished", -1, 1996);

有关bson_append_* 函数的完整列表,请参阅 libbsonAPI文档中的 bson_t。

您可以将 bson_get_data() 函数与标准C文件I/O 库结合使用,将BSON数据写入文件。以下示例将示例BSON文档写入名为 output.bson 的文件:

FILE *fp;
if ((fp = fopen("output.bson", "wb"))) {
fwrite(bson_get_data(doc), 1, doc->len, fp);
fclose(fp);
} else {
fprintf(stderr, "Failed to open file for writing.\n");
return EXIT_FAILURE;
}

您可以使用 bson_reader_t 类型从文件、内存地区或自定义回调中读取一系列BSON文档。以下示例从名为 example.bson 的文件中读取BSON文档,并打印每个文档的JSON表示形式:

bson_reader_t *reader;
bson_error_t error;
const bson_t *b;
char *str;
if (!((reader = bson_reader_new_from_file("example.json", &error)))) {
fprintf(stderr, "Failed to open file: %s\n", error.message);
return EXIT_FAILURE;
}
while ((b = bson_reader_read(reader, NULL))) {
str = bson_as_canonical_extended_json(b, NULL);
fprintf(stdout, "%s\n", str);
bson_free(str);
}
bson_reader_destroy(reader);

您可以使用 bson_json_reader_t 类型读取JSON文档序列并将其转换为 bson_t 文档。以下示例从名为 example.json 的文件中读取JSON文档,将每个文档转换为BSON格式,然后打印这些文档:

bson_json_reader_t *reader;
int b;
bson_error_t error;
bson_t doc = BSON_INITIALIZER;
if (!((reader = bson_json_reader_new_from_file("example.json", &error)))) {
fprintf(stderr, "Failed to open file: %s\n", error.message);
return EXIT_FAILURE;
}
while ((b = bson_json_reader_read(reader, &doc, &error))) {
if (b < 0) {
fprintf(stderr, "Failed to parse JSON: %s\n", error.message);
abort();
}
if (fwrite(bson_get_data(&doc), 1, doc.len, stdout) != doc.len) {
fprintf(stderr, "Failed to write BSON to stdout, exiting.\n");
exit(1);
}
bson_reinit(&doc);
}
bson_json_reader_destroy(reader);
bson_destroy(&doc);

您可以使用 bson_destroy() 函数释放为BSON文档分配的内存,如以下示例所示:

bson_t *doc = BCON_NEW("test", BCON_UTF8("example"));
// Operations using doc
bson_destroy(doc);

重要

当您使用完 bson_t实例时,请务必对其调用 bson_destroy(),以避免应用程序中的内存泄漏。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

聚合(Aggregation)

在此页面上