Docs HomeMongoDB Manual

MongoDB Extended JSON (v2)MongoDB扩展JSON(v2)

Important

Disambiguation消除歧义

The following page discusses MongoDB Extended JSON v2. For discussion on the Legacy MongoDB Extended JSON v1, see MongoDB Extended JSON (v1).下一页讨论MongoDB Extended JSON v2。有关旧版MongoDB扩展JSON v1的讨论,请参阅MongoDB扩展的JSON(v1)

For supported data types in mongosh, see mongosh Data Types.mongosh中支持的数据类型,请参阅mongosh数据类型

For supported data types in the legacy mongo shell, see /core/shell-types.有关旧版mongo shell中支持的数据类型,请参阅/core/shell-types

JSON can only directly represent a subset of the types supported by BSON. To preserve type information, MongoDB adds the following extensions to the JSON format.只能直接表示BSON支持的类型的子集。为了保留类型信息,MongoDB在JSON格式中添加了以下扩展。

  • Canonical Mode规范模式
    A string format that emphasizes type preservation at the expense of readability and interoperability. 一种字符串格式,强调以可读性和互操作性为代价的类型保留。That is, conversion from canonical to BSON will generally preserve type information except in certain specific cases.也就是说,从规范到BSON的转换通常会保留类型信息,除非在某些特定情况下。
  • Relaxed Mode松散模式
    A string format that emphasizes readability and interoperability at the expense of type preservation. That is, conversion from relaxed format to BSON can lose type information.一种字符串格式,强调可读性和互操作性,而牺牲了类型保存。也就是说,从宽松格式到BSON的转换可能会丢失类型信息。

Both formats conform to the JSON RFC and can be parsed by the various MongoDB drivers and tools.这两种格式都符合JSON RFC,并且可以通过各种MongoDB驱动程序和工具进行解析。

MongoDB Extended JSON v2 UsageMongoDB扩展JSON v2用法

Drivers驱动程序

The following drivers use the Extended JSON v2.0以下驱动程序使用Extended JSON v2.0

  • C
  • C++
  • Go
  • Java
  • Node
  • Perl
  • PHPC
  • Python
  • Scala

For C# and Ruby that use Legacy MongoDB Extended JSON v1, refer to MongoDB Extended JSON (v1).对于使用遗留MongoDB扩展JSON v1的C#和Ruby,请参阅MongoDB扩展的JSON(v1)

Extended JSON Methods扩展的JSON方法

MongoDB provides the following methods for Extended JSON:MongoDB为Extended JSON提供了以下方法:

Method方法Description描述
serializeSerializes a BSON object and returns the data in Extended JSON format. 序列化BSON对象并以扩展JSON格式返回数据。
EJSON.serialize( db.<collection>.findOne() )
deserializeConverts a serialized document to field and value pairs. 将序列化文档转换为字段和值对。The values have BSON types. 这些值具有BSON类型
EJSON.deserialize( <serialized object> )
stringifyConverts the element and type pairs in a deserialized object to strings. 将反序列化对象中的元素和类型对转换为字符串。
EJSON.stringify( <deserialized object> )
parseConverts strings into element and type pairs. 将字符串转换为元素和类型对。
EJSON.parse( <string> )

For usage examples, see Extended JSON Object Conversions below.有关用法示例,请参阅下面的扩展JSON对象转换

For additional details, see the documentation for:有关其他详细信息,请参阅以下文档:

MongoDB Database ToolsMongoDB数据库工具

Starting in version 4.2:从4.2版开始:

Binary二进制的Changes更改
bsondumpUses Extended JSON v2.0 (Canonical mode) format.使用Extended JSON v2.0(规范模式)格式。
mongodumpUse Extended JSON v2.0 (Canonical mode) format for the metadata. 元数据使用Extended JSON v2.0(规范模式)格式。Requires mongorestore version 4.2 or later that supports Extended JSON v2.0 (Canonical mode or Relaxed) format. 需要mongorestore 4.2或更高版本,支持Extended JSON v2.0(规范模式或宽松)格式。
Tip
In general, use corresponding versions of mongodump and mongorestore. 通常,使用mongodumpmongorestore的相应版本。That is, to restore data files created with a specific version of mongodump, use the corresponding version of mongorestore. 也就是说,要恢复使用特定版本的mongodump创建的数据文件,请使用相应版本的mongorestore
mongoexportCreates output data in Extended JSON v2.0 (Relaxed mode) by default.默认情况下,以Extended JSON v2.0(宽松模式)创建输出数据。
Creates output data in Extended JSON v2.0 (Canonical mode) if used with --jsonFormat.如果与--jsonFormat一起使用,则以Extended JSON v2.0(规范模式)创建输出数据。
mongoimportExpects import data to be in Extended JSON v2.0 (either Relaxed or Canonical mode) by default.默认情况下,导入数据应为Extended JSON v2.0(Relaxed或Canonical模式)。
Can recognize data that is in Extended JSON v1.0 format if the option --legacy is specified.如果指定了选项--legacy,则可以识别扩展JSON v1.0格式的数据。
Tip
In general, the versions of mongoexport and mongoimport should match. 通常,mongoexportmongoimport的版本应该匹配。That is, to import data created from mongoexport, you should use the corresponding version of mongoimport. 也就是说,要导入从mongoexport创建的数据,您应该使用相应版本的mongoimport

BSON Data Types and Associated RepresentationsBSON数据类型和关联表示

The following presents some common BSON data types and the associated representations in Canonical and Relaxed.以下介绍了一些常见的BSON数据类型以及规范和松弛中的相关表示。

The complete list is here.完整的列表在这里

Array

Canonical规范的Relaxed松散的
[ <elements> ]
<Same as Canonical>

Where the array elements are as follows:其中数组元素如下:

  • <elements>

    • Array elements use Extended JSON.数组元素使用扩展JSON。
    • To specify an empty array, omit the content [ ].若要指定一个空数组,请省略内容[]
Binary

Canonical规范的Relaxed松散的
{ "$binary":
{
"base64": "<payload>",
"subType": "<t>"
}
}
<Same as Canonical>

Where the values are as follows:其中值如下:

  • "<payload>"

    • Base64 encoded (with padding as "=") payload string.Base64编码(填充为“=”)的有效负载字符串。
  • "<t>"

    • A one- or two-character hex string that corresponds to a BSON binary subtype. 对应于BSON二进制子类型的一个或两个字符的十六进制字符串。See the extended bson documentation http://bsonspec.org/spec.html for subtypes available.请参阅扩展的bson文档http://bsonspec.org/spec.html可用的子类型。
Date

For dates between years 1970 and 9999, inclusive1970年至9999年(含):

Canonical规范的Relaxed松散的
{"$date": {"$numberLong": "<millis>"}}
{"$date": "<ISO-8601 Date/Time Format>"}

For dates before year 1970 or after year 9999适用于1970年之前或9999年之后的日期:

Canonical规范的Relaxed松散的
{"$date": {"$numberLong": "<millis>"}}
<Same as Canonical>

Where the values are as follows:其中值如下:

  • "<millis>"

    • A 64-bit signed integer as string. The value represents milliseconds relative to the epoch.作为字符串的64位带符号整数。该值表示相对于epoch的毫秒数。
  • "<ISO-8601 Date/Time Format>"

    • A date in ISO-8601 Internet Date/Time Format as string.ISO-8601 Internet日期/时间格式的字符串日期。
    • The date/time has a maximum time precision of milliseconds:日期/时间的最大时间精度为毫秒:

      • Fractional seconds have exactly 3 decimal places if the fractional part is non-zero.如果小数部分为非零,小数秒正好有3位小数。
      • Otherwise, fractional seconds SHOULD be omitted if zero.否则,如果为零,则应忽略小数秒。
Decimal128

Canonical规范的Relaxed松散的
{ "$numberDecimal": "<number>" }
<Same as Canonical>

Where the values are as follows:其中值如下:

Document

Canonical规范的Relaxed松散的
{ <content> }
<Same as Canonical>

Where the document contents are as follows:文件内容如下:

  • <content>

    • Name:value pairs that use Extended JSON.名称:使用扩展JSON的值对。
    • To specify an empty document, omit the content { }.若要指定空文档,请省略内容{ }
Double

For finite numbers:

Canonical规范的Relaxed松散的
{"$numberDouble": "<decimal string>" }
<non-integer number>

For infinite numbers or NAN对于无限数或NAN:

Canonical规范的Relaxed松散的
{"$numberDouble": <"Infinity"|"-Infinity"|"NaN"> }
<Same as Canonical>

Where the values are as follows:其中值如下:

  • "<decimal string>"

    • A 64-bit signed floating point as a string.作为字符串的64位带符号浮点。
  • <non-integer number>

    • A non-integer number. 一个非整数。Integer numbers are parsed as an integer instead of a double.整数被解析为整数而不是双精度。
Int64

Canonical规范的Relaxed松散的
{ "$numberLong": "<number>" }
<integer>

Where the values are as follows:其中值如下:

  • "<number>"

    • A 64-bit signed integer as string.作为字符串的64位带符号整数。
  • <integer>

    • A 64-bit signed integer.一个64位有符号整数。
Int32

Canonical规范的Relaxed松散的
{ "$numberInt": "<number>" }
<integer>

Where the values are as follows:其中值如下:

  • "<number>"

    • A 32-bit signed integer as a string.作为字符串的32位有符号整数。
  • <integer>

    • A 32-bit signed integer.一个32位有符号整数。
MaxKey

Canonical规范的Relaxed松散的
{ "$maxKey": 1 }
<Same as Canonical>

The MaxKey BSON data type compares higher than all other types. MaxKey BSON数据类型相比之下高于所有其他类型。See Comparison/Sort Order for more information on comparison order for BSON types.有关BSON类型的比较顺序的更多信息,请参阅比较/排序顺序

MinKey

Canonical规范的Relaxed松散的
{ "$minKey": 1 }
<Same as Canonical>

The MinKey BSON data type compares lower than all other types. 相比之下,MinKey BSON数据类型低于所有其他类型。See Comparison/Sort Order for more information on comparison order for BSON types.有关BSON类型的比较顺序的更多信息,请参阅比较/排序顺序

ObjectId

Canonical规范的Relaxed松散的
{ "$oid": "<ObjectId bytes>" }
<Same as Canonical>

Where the values are as follows:其中值如下:

  • "<ObjectId bytes>"

    • A 24-character, big-endian hexadecimal string that represents the ObjectId bytes.一个24个字符的大端十六进制字符串,表示ObjectId字节。
Regular Expression

Canonical规范的Relaxed松散的
{ "$regularExpression":
{
"pattern": "<regexPattern>",
"options": "<options>"
}
}
<Same as Canonical>

Where the values are as follows:其中值如下:

  • "<regexPattern>"

    • A string that corresponds to the regular expression pattern. 与正则表达式模式相对应的字符串。The string can contain valid JSON characters and unescaped double quote (") characters, but may not contain unescaped forward slash (/) characters.该字符串可以包含有效的JSON字符和未转义的双引号(")字符,但不能包含未转义的正斜杠(/)字符。
  • "<options>"

    • A string that specifies BSON regular expression options ('g', 'i', 'm' and 's') or an empty string "".指定BSON正则表达式选项('g'、'i'、'm'和's')的字符串或空字符串""
    • Options other than ('g', 'i', 'm' and 's') will be dropped when converting to this representation.转换为此表示形式时,将删除('g'、'i'、'm'和's')以外的选项。
    Important

    The options MUST be in alphabetical order.选项必须按字母顺序排列。

Timestamp

Canonical规范的Relaxed松散的
{"$timestamp": {"t": <t>, "i": <i>}}
<Same as Canonical>

Where the values are as follows:其中值如下:

  • <t>

    • A positive integer for the seconds since epoch.自epoch以来的秒数为正整数。
  • <i>

    • A positive integer for the increment.增量的正整数。

Examples实例

The following examples illustrate Extended JSON usage.以下示例说明了扩展JSON的使用。

Type Representations类型表示

Example Field Name字段名称示例Canonical Format规范格式Relaxed Format松散格式
"_id:"{"$oid":"5d505646cf6d4fe581014ab2"}{"$oid":"5d505646cf6d4fe581014ab2"}
"arrayField":["hello",{"$numberInt":"10"}]["hello",10]
"dateField":{"$date":{"$numberLong":"1565546054692"}}{"$date":"2019-08-11T17:54:14.692Z"}
"dateBefore1970":{"$date":{"$numberLong":"-1577923200000"}}{"$date":{"$numberLong":"-1577923200000"}}
"decimal128Field":{"$numberDecimal":"10.99"}{"$numberDecimal":"10.99"}
"documentField":{"a":"hello"}{"a":"hello"}
"doubleField":{"$numberDouble":"10.5"}10.5
"infiniteNumber"{"$numberDouble":"Infinity"}{"$numberDouble":"Infinity"}
"int32field":{"$numberInt":"10"}10
"int64Field":{"$numberLong":"50"}50
"minKeyField":{"$minKey":1}{"$minKey":1}
"maxKeyField":{"$maxKey":1}{"$maxKey":1}
"regexField":{"$regularExpression":{"pattern":"^H","options":"i"}}{"$regularExpression":{"pattern":"^H","options":"i"}}
"timestampField":{"$timestamp":{"t":1565545664,"i":1}}{"$timestamp":{"t":1565545664,"i":1}}

Extended JSON Object Conversions扩展的JSON对象转换

The following short examples create a document object and then convert the object to different forms using Extended JSON object conversion methods.下面的简短示例创建一个文档对象,然后使用ExtendedJSON对象转换方法将对象转换为不同的形式。

Setup设置

Create a document in the conversions collection:conversions集合中创建文档:

db.conversions.insertOne( { insertDate: new Date() } )

mongosh returns a document object:返回一个文档对象:

{
acknowledged: true,
insertedId: ObjectId("61fbaf25671c45f3f5f4074a")
}

EJSON.serialize

Serialize the data stored in a MongoDB document object:序列化存储在MongoDB文档对象中的数据:

serialized = EJSON.serialize( db.conversions.findOne() )

mongosh parses a JavaScript object and returns values using "$" prefixed types:解析JavaScript对象并使用前缀为"$"类型返回值:

{
_id: { '$oid': '61fbaf25671c45f3f5f4074a' },
insertDate: { '$date': '2022-02-03T10:32:05.230Z' }
}

EJSON.deserialize

Deserialize a serialized object:反序列化序列化对象:

EJSON.deserialize( serialized )

mongosh parses a JavaScript object and returns values using the default mongosh type form:解析JavaScript对象并使用默认的mongosh类型形式返回值:

{
_id: new ObjectId( "61fbaf25671c45f3f5f4074a" ),
insertDate: ISODate( "2022-02-03T10:32:05.230Z" )
}

EJSON.stringify

Convert an object to a string:将对象转换为字符串:

stringified = EJSON.stringify( db.conversions.findOne() )

mongosh outputs the elements of the converted object as strings:将转换后的对象的元素输出为字符串:

{
"_id": {"$oid":"61fbaf25671c45f3f5f4074a"},
"insertDate":{"$date":"2022-02-03T10:32:05.230Z"}
}

EJSON.parse

Parse a string to create an object:分析字符串以创建对象:

EJSON.parse( stringified )

mongosh returns the converted strings as documents:将转换后的字符串作为文档返回:

{
_id: new ObjectId("61fbaf25671c45f3f5f4074a"),
insertDate: ISODate("2022-02-03T10:32:05.230Z")
}