Docs 菜单
Docs 主页
/ /

扩展 JSON

在本指南中,您可以学习;了解在与MongoDB文档交互时如何使用扩展JSON数据格式。

JSON是一种人类可读的数据格式,用于表示对象值、数组、数字、字符串、布尔值和空值。此格式仅支持BSON数据类型的子集,而MongoDB正是使用该格式来存储数据。扩展JSON格式支持更多BSON 类型,定义了一设立以 "$" 为前缀的保留键,用于表示直接对应于BSON中每种类型的字段类型信息。

要学习;了解有关JSON、 BSON和扩展JSON的更多信息,请参阅 JSON和BSON资源以及扩展JSON MongoDB Server手册条目。

MongoDB扩展JSON提供字符串格式来表示BSON数据。 每种格式都符合JSON RFC 并满足特定的使用案例。

下表描述了每种扩展JSON格式:

名称
说明

规范

A string format that avoids loss of BSON type information during data conversions.
This format prioritizes type preservation at the loss of human-readability and interoperability with older formats. To specify this mode, pass bsoncxx::ExtendedJsonMode::k_canonical as a mode argument to the to_json() method.

宽松

A string format that describes BSON documents with some type information loss.
This format prioritizes human-readability and interoperability at the loss of certain type information. To specify this mode, pass bsoncxx::ExtendedJsonMode::k_relaxed as a mode argument to the to_json() method.

旧版

A string format that describes BSON documents with some type information loss.
This format matches Relaxed Extended JSON with some exceptions.
The C++ driver uses this mode by default.

注意

C++驾驶员将$uuid 扩展JSON类型从字符串解析为二进制子类型 的b_binary 4对象。有关$uuid 字段解析的更多信息,请参阅扩展JSON规范中解析 $uuid 字段的特殊规则部分。

以下示例显示了包含对象标识符、日期和长数字字段的文档,这些字段分别以扩展 JSON 格式表示。单击与要查看的示例格式相对应的选项卡:

{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": { "$numberLong": "1601499609" }},
"numViews": { "$numberLong": "36520312" }
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": "2020-09-30T18:22:51.648Z" },
"numViews": 36520312
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": "1601499771648" },
"numViews": 36520312
}

您可以通过调用 bsoncxx::from_json() 方法将扩展JSON字符串读入C++ BSON文档。此方法解析扩展JSON字符串并返回包含数据的 bsoncxx::document::value

以下示例展示如何使用 from_json() 方法将扩展JSON字符串读入BSON文档:

bsoncxx::document::value doc = bsoncxx::from_json(R"(
{
"_id": {"$oid": "507f1f77bcf86cd799439011"},
"myNumber": {"$numberLong": "4794261"}
}
)");

您可以使用 bsoncxx::to_json() 方法写入扩展JSON字符串。默认下,此方法返回传统格式的扩展JSON字符串,但您可以通过传递 mode 参数来指定规范或宽松格式。

注意

旧版本

传统格式选项指示C++驾驶员使用 Libbson 传统扩展JSON格式序列化BSON 类型。驾驶员将其用作默认模式。

有关更多信息,请参阅C驱动程序API文档中的传统扩展JSON页面。

bsoncxx::to_json() 方法可用于多种核心和标准库类型,包括 arraydocument。以下示例将 document 值转换为规范格式的扩展JSON字符串:

bsoncxx::builder::basic::document doc_builder;
doc_builder.append(kvp("myNumber", 11223344));
doc_builder.append(kvp("myString", "String value"));
bsoncxx::document::value doc = doc_builder.extract();
std::string json_str =
bsoncxx::to_json(doc, bsoncxx::ExtendedJsonMode::k_canonical);
std::cout << json_str << std::endl;
{"myNumber":{"$numberInt":"11223344"},"myString":"String value"}

要学习;了解有关本指南中提到的类型和方法的更多信息,请参阅以下API文档:

要学习;了解有关扩展JSON 的更多信息,请参阅MongoDB Server手册中的MongoDB扩展JSON 2(v)。

后退

BSON

在此页面上