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构造函数,使用Dateobject using theISODate()wrapper.ISODate()包装器返回Date对象。ISODate()constructor which returns a构造函数,使用Dateobject using theISODate()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 从1.8.0开始,ObjectId wrapper no longer accepts:ObjectId包装器不再接受:
- ObjectId.prototype.generate
- ObjectId.prototype.getInc
- ObjectId.prototype.get_inc
- ObjectId.getInc
Tip
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, 如果字段的值是一个可以转换为32位整数的数字,mongosh will store it as Int32. mongosh会将其存储为Int32。If 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连接到同一集合,则默认的Int32和Double类型可能会存储不一致。
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
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 MongoDB在oplog内部使用BSON时间戳。Timestamp type works similarly to the Java Timestamp type. Use the Date type for operations involving dates.Timestamp类型的工作方式与Java Timestamp类型类似。对于涉及日期的操作,请使用Date类型。
A Timestamp signature has two optional parameters.Timestamp签名有两个可选参数。
Timestamp( { "t": <integer>, "i": <integer> } )
t | integer | ||
i | integer | 1 | 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 Javascript typeof operator returns generic values such as number or object rather than the more specific Int32 or ObjectId.typeof运算符返回通用值,如number或object,而不是更具体的Int32或ObjectId。
Javascript's Javascript的instanceof operator is not reliable. For example, instanceof assigns BSON values in a server response to a different base class than user supplied values.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()帮助程序中的myDate的Date值:
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类型页面上给出。
| |
| |
| |
| |
| |
| |
| |
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: 4是Decimal128,因此未被选中。
Note, however, that 但是请注意,{ "value": 1 } returns both Int32 and Long types.{ "value": 1 }同时返回Int32和Long类型。
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纪元值1627811580将ts时间设置为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()进行类型检查
$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返回其类型