Docs Home / mongosh / Reference

Data Types数据类型

MongoDB stores data using BSON, which supports additional data types that aren't available in JSON. MongoDB使用BSON存储数据,BSON支持JSON中不可用的其他数据类型。The mongosh shell has better data type support for drivers than the legacy mongo shell.mongosh shell对驱动程序的数据类型支持比传统mongoshell更好。

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

Date

mongosh provides various methods to return the date, either as a string or as a Date object:提供了各种方法来返回日期,可以是字符串形式,也可以是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. To generate a new ObjectId, use the following operation in mongosh:提供围绕ObjectId数据类型的ObjectId()包装器类。要生成新的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

Double

The Double() constructor can be used to explicitly specify a double:Double()构造函数可用于显式指定Double:

db.types.insertOne(
{
"_id": 2,
"value": Double(1),
"expectedType": "Double"
}
)

Note

If field's value is a number that 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. To specify the value type, use the Double() or Int32() constructors.如果没有,mongosh默认将数字存储为Double。要指定值类型,请使用Double()Int32()构造函数。

Int32

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. 在传统的mongo shell中,NumberLong()接受字符串或整数值。In mongosh, NumberLong() only accepts string values. mongosh中,NumberLong()只接受字符串值。Long() provides methods to manage conversions to and from 64-bit values.Long()提供了管理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. The Timestamp type works similarly to the Java Timestamp type. Use the Date type for operations involving dates.MongoDB在oplog内部使用BSON时间戳Timestamp类型的工作方式与Java Timestamp类型类似。对于涉及日期的操作,请使用Date类型。

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

Timestamp( { "t": <integer>, "i": <integer> } )
Parameter参数Type类型Default默认Definition定义
tintegerCurrent time since UNIX epoch.UNIX时代以来的当前时间。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.可选。用于在给定秒内有多个操作时进行排序。如果不使用ti没有效果。

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,而不是更具体的Int32或ObjectId。

Javascript's instanceof operator is not reliable. For example, instanceof assigns BSON values in a server response to a different base class than user supplied values.Javascript的instanceof运算符不可靠。例如,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>. The type names and aliases are given on the BSON types page.此表显示了相应<QUERY>db.types.find( <QUERY> )命令的结果。类型名称和别名在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.01的Double表示。文档_id: 4Decimal128,因此未被选中。

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

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

Consider the typeExample collection. This collection consists of two identical documents, { "a": 1 }. 考虑typeExample集合。此集合由两个相同的文档组成,{ "a": 1 }The first document was created in the legacy mongo shell, the second document was created in mongosh.第一个文档是在遗留的mongo shell中创建的,第二个文档是用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. In the mongosh document the value was stored as type int.在第一个在遗留mongo shell中创建的文档中,该值被存储为double。在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. Notice that even though all three entries were stamped in the same second, the interval was incremented on each one.运行db.flights.find({})查看时间戳。请注意,即使所有三个条目都在同一秒内盖章,间隔也会在每个条目上递增。

[
{
_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纪元值1627811580ts时间设置为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. For example, the output of db.collection.find() is a Cursor.检查对象constructor以确定类型。例如,db.collection.find()的输出是一个Cursor(游标)。

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