Database Manual / Introduction / BSON Types

MongoDB Extended扩展的 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扩展JSON v2。有关遗留MongoDB扩展JSON v1的讨论,请参阅MongoDB扩展JSON(v1)

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

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格式中添加了以下扩展。

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 support Extended JSON v2.0:以下驱动程序支持Extended JSON v2.0:

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

Extended JSON Methods扩展JSON方法

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

Method方法Description描述
serialize

Serializes a BSON object and returns the data in Extended JSON format.序列化BSON对象并以扩展JSON格式返回数据。

EJSON.serialize( db.<collection>.findOne() )
deserialize

Converts a serialized document to field and value pairs. The values have BSON types.将序列化文档转换为字段和值对。这些值具有BSON类型

EJSON.deserialize( <serialized object> )
stringify

Converts the element and type pairs in a deserialized object to strings.将反序列化对象中的元素和类型对转换为字符串。

EJSON.stringify( <deserialized object> )
parse

Converts 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.使用扩展JSON v2.0(规范模式)格式。
mongodump

Use Extended JSON v2.0 (Canonical mode) format for the metadata. 元数据使用扩展JSON v2.0(规范模式)格式。Requires mongorestore version 4.2 or later that supports Extended JSON v2.0 (Canonical mode or Relaxed) format.需要支持扩展JSON v2.0(规范模式或宽松)格式的mongorestore 4.2或更高版本。

In general, use corresponding versions of mongodump and mongorestore. 一般来说,使用相应版本的mongodumpmongorestoreTo restore data files created with a specific version of mongodump, use the corresponding version of mongorestore.要还原使用特定版本的mongodump创建的数据文件,请使用相应版本的mongorestore

mongoexport

Creates 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一起使用,则以扩展JSON v2.0(规范模式)创建输出数据。

mongoimport

Expects import data to be in Extended JSON v2.0 (either Relaxed or Canonical mode) by default.默认情况下,导入数据应为Extended JSON v2.0(松弛模式或规范模式)。

Can recognize data that is in Extended JSON v1.0 format if the option --legacy is specified.如果指定了选项--legacy,则可以识别Extended JSON v1.0格式的数据。

In general, the versions of mongoexport and mongoimport should match. 一般来说,mongoexportmongoimport的版本应该匹配。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数据类型以及Canonical和Relaxed中的相关表示。

The complete list is here.完整的名单在这里

Array

CanonicalRelaxed
[ <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

CanonicalRelaxed
{ "$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. See the extended bson documentation http://bsonspec.org/spec.html for subtypes available.与BSON二进制子类型对应的一个或两个字符的十六进制字符串。请参阅扩展的bson文档http://bsonspec.org/spec.html以了解于可用的亚型。
Date

For dates between years 1970 and 9999, inclusive:对于1970年至9999年(含)之间的日期:

CanonicalRelaxed
{"$date": {"$numberLong": "<millis>"}}
{"$date": "<ISO-8601 Date/Time Format>"}

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

CanonicalRelaxed
{"$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位带符号整数,作为字符串。该值表示相对于纪元的毫秒数。
  • "<ISO-8601 Date/Time Format>"

    • A date in ISO-8601 Internet Date/Time Format as string.ISO-8601互联网日期/时间格式的日期字符串。
    • 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

CanonicalRelaxed
{ "$numberDecimal": "<number>" }
<Same as Canonical>

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

Document

CanonicalRelaxed
{ <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:对于有限数:

CanonicalRelaxed
{"$numberDouble": "<decimal string>" }
<non-integer number>

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

CanonicalRelaxed
{"$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

CanonicalRelaxed
{ "$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

CanonicalRelaxed
{ "$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

CanonicalRelaxed
{ "$maxKey": 1 }
<Same as Canonical>

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

MinKey

CanonicalRelaxed
{ "$minKey": 1 }
<Same as Canonical>

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

ObjectId

CanonicalRelaxed
{ "$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

CanonicalRelaxed
{ "$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. You must specify the options in alphabetical order. For information on the supported options, see $options.指定BSON正则表达式选项的字符串。您必须按字母顺序指定选项。有关支持的选项的信息,请参阅$options
Timestamp

CanonicalRelaxed
{"$timestamp": {"t": <t>, "i": <i>}}
<Same as Canonical>

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

  • <t>

    • A positive integer for the seconds since 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}}
"uuid":{"$uuid":"3b241101-e2bb-4255-8caf-4136c566a962"}{"$uuid":"3b241101-e2bb-4255-8caf-4136c566a962"}

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.以下简短示例创建了一个文档对象,然后使用扩展的JSON对象转换方法将该对象转换为不同的形式。

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")
}