Data Types数据类型
On this page本页内容
- Date
- ObjectId
- Int32
- Long
- Decimal128
Equality and Sort Order相等和排序顺序- Timestamp
Type Checking类型检查Examples示例Return Date as a String字符串形式的返回日期Return返回Date
Numeric Types数值类型Default Numeric Type Consistency默认数字类型一致性Timestamp a New Document为新文档添加时间戳Create a Custom Timestamp创建自定义时间戳Type Checking with使用$type()
进行类型检查$Type
()Type Checking with a Constructor使用构造函数进行类型检查
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.mongo
shell相比,MongoDB shell(mongosh
)具有更好地与MongoDB驱动程序使用的默认类型保持一致的类型处理。
This document highlights changes in type usage between 本文档重点介绍了mongosh
and the legacy mongo
shell. mongosh
和传统mongo
shell之间类型使用的变化。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 theISODate()
wrapper.ISODate()
包装返回Date
对象。ISODate()
constructor which returns a构造函数使用Date
object using theISODate()
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 要生成新的ObjectId,请在mongosh
: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
See also:
Int32
If a number 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
. mongosh
默认将数字存储为Double
。Numerical 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()Int32() constructor can be used to explicitly specify 32-bit integers.
构造函数可用于显式指定32位整数。
db.types.insertOne(
{
"_id": 1,
"value": Int32("1"),
"expectedType": "Int32"
}
)
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()Long() constructor can be used to explicitly specify a 64-bit integer.
构造函数可用于显式指定64位整数。
db.types.insertOne(
{
"_id": 3,
"value": Long("1"),
"expectedType": "Long"
}
)
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"
}
)
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> } )
t | integer | Current time since UNIX epoch. | |
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. 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()
帮助程序中的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>
. <QUERY>
的db.types.find( <QUERY> )
命令的结果。The type names and aliases are given on the BSON types page.类型名称和别名在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. 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
.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
. mongo
shell中创建的第一个文档中,该值存储为double
。In 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 epoch值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()
$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