Overview
在本指南中,您可以学习;了解在与MongoDB文档交互时如何使用扩展JSON数据格式。
JSON是一种人类可读的数据格式,用于表示对象值、数组、数字、字符串、布尔值和空值。此格式仅支持BSON数据类型的子集,而MongoDB正是使用该格式来存储数据。扩展JSON格式支持更多BSON 类型,定义了一设立以 "$
" 为前缀的保留键,用于表示直接对应于BSON中每种类型的字段类型信息。
要学习;了解有关JSON、 BSON和扩展JSON的更多信息,请参阅 JSON和BSON资源以及扩展JSON MongoDB Server手册条目。
扩展 JSON 格式
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. |
宽松 | 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. The .NET/C# Driver uses Relaxed mode by default. |
Shell | A string format that matches the syntax used in the MongoDB shell. This format prioritizes compatibility with the MongoDB shell, which often uses
JavaScript functions to represent types. |
注意
.NET/ C#驱动程序将$uuid
扩展JSON类型从字符串解析为二进制子类型 的BsonBinary
4对象。有关$uuid
字段解析的更多信息,请参阅扩展JSON规范中解析 $uuid 字段的特殊规则部分。
扩展 JSON 示例
以下示例显示了包含对象标识符、日期和长数字字段的文档,这些字段分别以扩展 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": ObjectId("573a1391f29313caabcd9637"), "createdAt": ISODate("2020-09-30T18:22:51.648Z"), "numViews": NumberLong("36520312") }
读取扩展 JSON
您可以使用 BsonDocument.Parse()
方法将扩展JSON文档读入C#对象。以下示例将扩展JSON 文档读入 BsonDocument
对象:
var ejson = "{\n\"_id\": { \"$oid\": \"573a1391f29313caabcd9637\" },\n \"createdAt\": { \"$date\": { \"$numberLong\": \"1601499609\" }},\n\"numViews\": { \"$numberLong\": \"36520312\" }\n}\n\n"; var document = BsonDocument.Parse(ejson); Console.WriteLine(document.ToJson());
{ "_id" : { "$oid" : "573a1391f29313caabcd9637" }, "createdAt" : { "$date" : "1970-01-19T12:51:39.609Z" }, "numViews" : 36520312 }
写入扩展 JSON
您可以通过对 BsonDocument
对象或自定义类调用 ToJson()
方法来写入扩展JSON字符串。您必须指定一个 JsonWriterSettings
对象作为参数,其中 OutputMode
属性设立为所需的扩展JSON格式。
请考虑以下自定义类:
public class MyDocument { public ObjectId Id { get; set; } public DateTime CreatedAt { get; set; } public long NumViews { get; set; } }
以下示例通过将 CanonicalExtendedJson
值指定为 OutputMode
属性,以扩展JSON格式输出 MyDocument
的实例:
var document = new MyDocument(); document.Id = ObjectId.GenerateNewId(); document.CreatedAt = DateTime.UtcNow; document.NumViews = 1234567890; var json = document.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.CanonicalExtendedJson }); Console.WriteLine(json);
{ "_id" : { "$oid" : "68094769744af81f368ff1c1" }, "CreatedAt" : { "$date" : { "$numberLong" : "1745438569994" } }, "NumViews" : { "$numberLong" : "1234567890" } }
API 文档
要进一步学习;了解可用于处理JSON文档的方法和类,请参阅以下API文档: