Docs HomeMongoDB Shell

Data Types数据类型

MongoDB Server stores data using the BSON format which supports some additional data types that are not available using the JSON format. MongoDB Server使用BSON格式存储数据,BSON格式支持一些JSON格式无法提供的其他数据类型。Compared to the legacy mongo shell, MongoDB Shell (mongosh) has type handling which is better aligned with the default types used by the MongoDB drivers.与传统的mongoshell相比,MongoDB shell(mongosh)具有更好地与MongoDB驱动程序使用的默认类型保持一致的类型处理。

This document highlights changes in type usage between mongosh and the legacy mongo shell. 本文档重点介绍了mongosh和传统mongoshell之间类型使用的变化。See the Extended JSON reference for additional information on supported types.有关支持的类型的其他信息,请参阅Extended JSON参考。

Date

mongosh provides various methods to return the date, either as a string or as a Date object:mongosh提供了各种方法来返回日期,可以是字符串,也可以是Date对象:

  • Date() method which returns the current date as a string.方法,该方法将当前日期作为字符串返回。
  • new Date() constructor which returns a Date object using the ISODate() wrapper.构造函数,该构造函数使用ISODate()包装返回Date对象。
  • ISODate() constructor which returns a Date object using the ISODate() wrapper.构造函数使用ISODate()包装返回Date对象。

ObjectId

mongosh provides the ObjectId() wrapper class around the ObjectId data type. mongosh围绕ObjectId数据类型提供了ObjectId()包装类。To generate a new ObjectId, use the following operation in mongosh:要生成新的ObjectId,请在mongosh中使用以下操作:

new ObjectId

Starting in 1.8.0, the ObjectId wrapper no longer accepts:从1.8.0开始,ObjectId包装器不再接受:

  • ObjectId.prototype.generate
  • ObjectId.prototype.getInc
  • ObjectId.prototype.get_inc
  • ObjectId.getInc
Tip

See also:

Int32

If a number can be converted to a 32-bit integer, mongosh will store it as Int32. 如果一个数字可以转换为32位整数,mongosh会将其存储为Int32If not, mongosh defaults to storing the number as a Double. 如果没有,mongosh默认将数字存储为DoubleNumerical values that are stored as Int32 in mongosh would have been stored by default as Double in the mongo shell.mongosh中存储为Int32的数值在mongo shell中默认存储为Double

The Int32() constructor can be used to explicitly specify 32-bit integers.Int32()构造函数可用于显式指定32位整数。

db.types.insertOne(
{
"_id": 1,
"value": Int32("1"),
"expectedType": "Int32"
}
)
Warning

Default Int32 and Double types may be stored inconsistently if you connect to the same collection using both mongosh and the legacy mongo shell.如果同时使用mongosh和传统mongo shell连接到同一集合,则默认Int32Double类型的存储可能不一致。

Long

The Long() constructor can be used to explicitly specify a 64-bit integer.Long()构造函数可用于显式指定64位整数。

db.types.insertOne(
{
"_id": 3,
"value": Long("1"),
"expectedType": "Long"
}
)
Note

In the legacy mongo shell NumberLong() accepted either a string or integer value. 在遗留的mongoshell中,NumberLong()接受字符串或整数值。In mongosh, NumberLong() only accepts string values. mongosh中,NumberLong()只接受字符串值。Long() provides methods to manage conversions to and from 64-bit values.提供了管理64位值之间的转换的方法。

Decimal128

Decimal128() values are 128-bit decimal-based floating-point numbers that emulate decimal rounding with exact precision.值是基于128位十进制的浮点数,以精确的精度模拟十进制舍入。

This functionality is intended for applications that handle monetary data, such as financial, tax, and scientific computations.此功能适用于处理货币数据的应用程序,如财务、税务和科学计算。

The Decimal128 BSON type uses the IEEE 754 decimal128 floating-point numbering format which supports 34 decimal digits (i.e. significant digits) and an exponent range of −6143 to +6144.Decimal128 BSON类型使用IEEE 754 Decimal128浮点编号格式,该格式支持34位十进制数字(即有效数字)和6143到+6144的指数范围。

db.types.insertOne(
{
"_id": 5,
"value": Decimal128("1"),
"expectedType": "Decimal128"
}
)
Note

To use the Decimal128 data type with a MongoDB driver, be sure to use a driver version that supports it.要将Decimal128数据类型与MongoDB驱动程序一起使用,请确保使用支持它的驱动程序版本。

Equality and Sort Order相等和排序顺序

Values of the Decimal128 type are compared and sorted with other numeric types based on their actual numeric value. Decimal128类型的值根据其实际数值与其他数值类型进行比较和排序。 Numeric values of the binary-based Double type generally have approximate representations of decimal-based values and may not be exactly equal to their decimal representations.基于二进制的Double类型的数值通常具有基于十进制的值的近似表示,并且可能不完全等于其十进制表示。

Timestamp

MongoDB uses a BSON Timestamp internally in the oplog. MongoDB在oplog内部使用BSON时间戳The Timestamp type works similarly to the Java Timestamp type. Timestamp类型与Java时间戳类型的工作原理类似。Use the Date type for operations involving dates.对于涉及日期的操作,请使用Date类型。

A Timestamp signature has two optional parameters.Timestamp签名有两个可选参数。

Timestamp( { "t": <integer>, "i": <integer> } )
Parameter参数Type类型Default默认值Definition定义
tintegerCurrent time since UNIX epoch.Optional. A time in seconds.可选择的以秒为单位的时间。
iinteger1Optional. 可选择的Used for ordering when there are multiple operations within a given second. 用于在给定的一秒内有多个操作时进行排序。i has no effect if used without t.如果不使用t,则i无效。

For usage examples, see Timestamp a New Document, Create a Custom Timestamp.有关用法示例,请参阅为新文档添加时间戳创建自定义时间戳

Type Checking类型检查

Use the $type query operator or examine the object constructor to determine types.使用$type查询运算符或检查对象构造函数来确定类型。

The Javascript typeof operator returns generic values such as number or object rather than the more specific Int32 or ObjectId.Javascript typeof运算符返回诸如numberobject之类的泛型值,而不是更具体的Int32ObjectId

Javascript's instanceof operator is not reliable. Javascript的instanceof运算符不可靠。For example, instanceof assigns BSON values in a server response to a different base class than user supplied values.例如,instanceof将服务器响应中的BSON值分配给与用户提供的值不同的基类。

For usage examples, see Type Checking with $type() and Type Checking with a Constructor.使用构造函数进行类型检查。有关用法示例,请参阅使用$Type()进行类型检查使用构造函数进行类型检查

Examples示例

Return Date as a String字符串形式的返回日期

To return the date as a string, use the Date() method, as in the following example:要将日期作为字符串返回,请使用date()方法,如下例所示:

var myDateString = Date();

To print the value of the variable, type the variable name in the shell, as in the following:要打印变量的值,请在shell中键入变量名,如下所示:

myDateString

The result is the value of myDateString:结果是myDateString的值:

Wed Dec 19 2012 01:03:25 GMT-0500 (EST)

To verify the type, use the typeof operator, as in the following:要验证类型,请使用typeof运算符,如下所示:

typeof myDateString

The operation returns string.该操作返回string

Return 返回Date

mongosh wraps objects of Date type with the ISODate helper; however, the objects remain of type Date.mongosh使用ISODate辅助对象包装Date类型的对象;但是,对象仍然是Date类型。

The following example uses both the new Date() constructor and the ISODate() constructor to return Date objects.以下示例使用new Date()构造函数和ISODate()构造器来返回Date对象。

var myDate = new Date();
var myDateInitUsingISODateWrapper = ISODate();

You can use the new operator with the ISODate() constructor as well.您也可以将new运算符与ISODate()构造函数一起使用。

To print the value of the variable, type the variable name in the shell, as in the following:要打印变量的值,请在shell中键入变量名,如下所示:

myDate

The result is the Date value of myDate wrapped in the ISODate() helper:结果是包装在ISODate()帮助程序中的myDateDate值:

ISODate("2012-12-19T06:01:17.171Z")

To verify the type:要验证类型,请执行以下操作:

var myDate = ISODate("2021-03-21T06:00:00.171Z")
Object.prototype.toString.call(myDate) === "[object Date]"

The operation returns true.操作返回true

Numeric Types数值类型

Consider the types collection:请考虑types集合:

{ _id: 1, value: 1, expectedType: 'Int32' },
{ _id: 2, value: Long("1"), expectedType: 'Long' },
{ _id: 3, value: 1.01, expectedType: 'Double' },
{ _id: 4, value: Decimal128("1.01"), expectedType: 'Decimal128' },
{ _id: 5, value: 3200000001, expectedType: 'Double' }

This table shows the results of the db.types.find( <QUERY> ) command for the corresponding <QUERY>. 此表显示了相应的<QUERY>db.types.find( <QUERY> )命令的结果。The type names and aliases are given on the BSON types page.类型名称和别名在BSON类型页面上给出。

Query查询Results结果
{
"value":
{
$type: "int"
}
}
{
_id: 1,
value: 1,
expectedType: 'Int32'
}
{
"value":
{
$type: "long"
}
}
{
_id: 2,
value: Long("1"),
expectedType: 'Long'
}
{
"value":
{
$type: "decimal"
}
}
{
_id: 4,
value: Decimal128("1"),
expectedType: 'Decimal128'
}
{
"value":
{
$type: "double"
}
}
{
_id: 3,
value: 1.01,
expectedType: 'Double'
}
{
_id: 5,
value: 3200000001,
expectedType: 'Double'
}
{
"value":
{
$type: "number"
}
}
{
_id: 1,
value: 1,
expectedType: 'Int32'
}
{
_id: 2,
value: Long("1"),
expectedType: 'Long'
}
{
_id: 3,
value: 1.01,
expectedType: 'Double'
}
{
_id: 4,
value: Decimal128("1.01"),
expectedType: 'Decimal128'
}
{
_id: 5,
value: 3200000001,
expectedType: 'Double'
}
{
"value": 1.01
}
{
_id: 3,
value: 1.01,
expectedType: 'Double'
}
{
"value": 1
}
{
_id: 1,
value: 1,
expectedType: 'Int32'
}
{
_id: 2,
value: Long("1"),
expectedType: 'Long'
}

The query { "value": 1.01 } implicitly searches for the Double representation of 1.01. Document _id: 4 is a Decimal128 so it is not selected.查询{ "value": 1.01 }隐式搜索1.01Double表示。文档_id:4Decimal128,因此未选中它。

Note, however, that { "value": 1 } returns both Int32 and Long types.但是,请注意,{ "value": 1 }同时返回Int32Long类型。

Default Numeric Type Consistency默认数字类型一致性

Consider the typeExample collection. 请考虑typeExample集合。This collection consists of two identical documents, { "a": 1 }. 此集合由两个相同的文档组成,{ "a": 1 }The first document was created in the legacy mongo shell, the second document was created in mongosh.第一个文档是在遗留的mongoshell中创建的,第二个文档是用mongosh创建的。

We can use the $type operator in an aggregation pipeline to see the type that was assigned in each shell.我们可以在聚合管道中使用$type运算符来查看在每个shell中分配的类型。

db.typeExample.aggregate(
[
{
$project:
{
"valueType":
{
"$type": "$a"
},
"_id": 0
}
}
]
)

In the first document, created in the legacy mongo shell, the value was stored as a double. 在遗留mongoshell中创建的第一个文档中,该值存储为doubleIn the mongosh document the value was stored as type int.mongosh文档中,该值存储为int类型。

[
{
valueType: 'double' // inserted in legacy mongo shell
},
{
valueType: 'int' // inserted in mongosh
}
]

Timestamp a New Document为新文档添加时间戳

Use Timestamp() without parameters to insert multiple documents using the default settings:使用不带参数的Timestamp()可以使用默认设置插入多个文档:

db.flights.insertMany(
[
{ arrival: "true", ts: Timestamp() },
{ arrival: "true", ts: Timestamp() },
{ arrival: "true", ts: Timestamp() }
]
)

Run db.flights.find({}) to see the timestamps. 运行db.flights.find({})查看时间戳。Notice that even though all three entries were stamped in the same second, the interval was incremented on each one.请注意,尽管所有三个条目都在同一秒内盖章,但每个条目的间隔都会增加。

[
{
_id: ObjectId("6114216907d84f5370391919"),
arrival: 'true',
ts: Timestamp({ t: 1628709225, i: 1 })
},
{
_id: ObjectId("6114216907d84f537039191a"),
arrival: 'true',
ts: Timestamp({ t: 1628709225, i: 2 })
},
{
_id: ObjectId("6114216907d84f537039191b"),
arrival: 'true',
ts: Timestamp({ t: 1628709225, i: 3 })
}
]

Create a Custom Timestamp创建自定义时间戳

Use custom parameters to insert multiple documents with a specific Timestamp.使用自定义参数可以插入具有特定Timestamp的多个文档。

This operation inserts three documents into the flights collection and uses the UNIX epoch value 1627811580 to set the ts times to 9:53 GMT on August 1, 2021.此操作将三个文档插入flights集合,并使用UNIX epoch1627811580ts时间设置为2021年8月1日格林尼治标准时间9:53。

db.flights.insertMany(
[
{ arrival: "true", ts: Timestamp(1627811580, 10) },
{ arrival: "true", ts: Timestamp(1627811580, 20) },
{ arrival: "true", ts: Timestamp(1627811580, 30) }
]
)

The resulting documents look like this:生成的文档如下所示:

[
{
_id: ObjectId("6123d8315e6bba6f61a1031c"),
arrival: 'true',
ts: Timestamp({ t: 1627811580, i: 10 })
},
{
_id: ObjectId("6123d8315e6bba6f61a1031d"),
arrival: 'true',
ts: Timestamp({ t: 1627811580, i: 20 })
},
{
_id: ObjectId("6123d8315e6bba6f61a1031e"),
arrival: 'true',
ts: Timestamp({ t: 1627811580, i: 30 })
}
]

Type Checking with $type()使用$Type()进行类型检查

The $type query operator accepts either a string alias or a numeric code corresponding to the data type. $type查询运算符接受与数据类型对应的字符串别名或数字代码。See BSON Types for a list of BSON data types and their corresponding numeric codes.有关BSON数据类型及其相应数字代码的列表,请参阅BSON类型

For example, these checks for the Decimal128 type are equivalent:例如,Decimal128类型的这些检查是等效的:

db.types.find( { "value": { $type: "decimal" } } )
db.types.find( { "value": { $type: 19 } } )

Type Checking with a Constructor使用构造函数进行类型检查

Examine the object constructor to determine the type. 检查对象constructor以确定类型。For example, the output of db.collection.find() is a Cursor.例如,db.collection.find()的输出是一个Cursor

var findResults = db.housing.find({"multiUnit": true} )
findResults.constructor.name // Returns the type