Data Types in the mongo Shellmongo Shell中的数据类型

On this page本页内容

Note

The following document pertains to the mongo shell included in the MongoDB Server Download. 以下文档涉及MongoDB服务器下载中包含的mongo shell。For information on the new MongoDB Shell, mongosh, refer to the mongosh Documentation.有关新MongoDB外壳mongosh的信息,请参阅mongosh文档

To understand the differences between the two shells, see Comparison of the mongo Shell and mongosh.要了解这两种外壳之间的差异,请参阅mongo外壳和mongosh外壳的比较

MongoDB BSON provides support for additional data types than JSON. MongoDB BSON提供了对JSON以外的其他数据类型的支持。Drivers provide native support for these data types in host languages and the mongo shell also provides several helper classes to support the use of these data types in the mongo JavaScript shell. 驱动程序在主机语言中为这些数据类型提供了本机支持,mongo shell还提供了几个帮助器类来支持在mongo JavaScript shell中使用这些数据类型。See the Extended JSON reference for additional information.有关更多信息,请参阅扩展JSON参考

Types类型

Date

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

  • 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对象。

Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).在内部,Date对象存储为有符号64位整数,表示自Unix纪元(1970年1月1日)以来的毫秒数。

Not all database operations and drivers support the full 64-bit range. 并非所有数据库操作和驱动程序都支持完整的64位范围。You may safely work with dates with years within the inclusive range 0 through 9999.您可以安全地使用年数在09999之间的日期。

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

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

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

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

You can use the new operator with the ISODate() constructor as well.您还可以将新运算符与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的日期值:

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

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

myDate instanceof Date
myDateInitUsingISODateWrapper instanceof Date

The operation returns true for both.这两个操作都返回true

ObjectId

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

new ObjectId

NumberLong

The mongo shell treats all numbers as floating-point values by default. 默认情况下,mongo shell将所有数字视为浮点值。The mongo shell provides the NumberLong() wrapper to handle 64-bit integers.mongo shell提供NumberLong()包装来处理64位整数。

The NumberLong() wrapper accepts the long as a string:NumberLong()包装器接受长字符串:

NumberLong("2090845886852")

The following examples use the NumberLong() wrapper to write to the collection:以下示例使用NumberLong()包装器写入集合:

db.collection.insertOne( { _id: 10, calc: NumberLong("2090845886852") } )
db.collection.updateOne( { _id: 10 },
                      { $set:  { calc: NumberLong("2555555000000") } } )
db.collection.updateOne( { _id: 10 },
                      { $inc: { calc: NumberLong("5") } } )

Retrieve the document to verify:检索要验证的文档:

db.collection.findOne( { _id: 10 } )

In the returned document, the calc field contains a NumberLong object:在返回的文档中,calc字段包含一个NumberLong对象:

{ "_id" : 10, "calc" : NumberLong("2555555000005") }

If you use the $inc to increment the value of a field that contains a NumberLong object by a float, the data type changes to a floating point value, as in the following example:如果使用$inc将包含NumberLong对象的字段的值增加一个浮点,则数据类型将更改为浮点值,如下例所示:

  1. Use $inc to increment the calc field by 5, which the mongo shell treats as a float:使用$inccalc字段增加5,mongo shell将其视为浮点:

    db.collection.updateOne( { _id: 10 },
                          { $inc: { calc: 5 } } )
  2. Retrieve the updated document:检索更新的文档:

    db.collection.findOne( { _id: 10 } )

    In the updated document, the calc field contains a floating point value:在更新的文档中,calc字段包含一个浮点值:

    { "_id" : 10, "calc" : 2555555000010 }

Note

Although the NumberLong() constructor accepts integer values from the mongo shell (i.e. without quotes), this is not recommended. 尽管NumberLong()构造函数接受来自mongo shell的integer(即不带引号),但不建议这样做。Specifying an integer value larger than JavaScript’s defined Number.MAX_SAFE_INTEGER (which is the number 2^53 - 1) may lead to unexpected behavior.指定大于JavaScript定义的Number.MAX_SAFE_integer(即数字2^53-1)的整数值可能会导致意外行为。

NumberInt

The mongo shell treats all numbers as floating-point values by default. 默认情况下,mongo shell将所有数字视为浮点值。The mongo shell provides the NumberInt() constructor to explicitly specify 32-bit integers.mongo shell提供numberrint()构造函数来显式指定32位整数。

NumberDecimal

New in version 3.4.版本3.4中的新功能。

The mongo shell treats all numbers as 64-bit floating-point double values by default. 默认情况下,mongo shell将所有数字视为64位浮点双精度值。The mongo shell provides the NumberDecimal() constructor to explicitly specify 128-bit decimal-based floating-point values capable of emulating decimal rounding with exact precision. mongo shell提供NumberDecimal()构造函数,以显式指定基于128位十进制的浮点值,该浮点值能够模拟精确的十进制舍入。This functionality is intended for applications that handle monetary data, such as financial, tax, and scientific computations.此功能适用于处理货币数据的应用程序,如金融、税务和科学计算。

The decimal 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.decimal BSON类型使用IEEE 754 decimal128浮点编号格式,支持34位十进制数字(即有效数字),指数范围为6143至+6144。

The NumberDecimal() constructor accepts the decimal value as a string:NumberDecimal()构造函数接受十进制值作为字符串:

NumberDecimal("1000.55")

The value is stored in the database as follows:该值存储在数据库中,如下所示:

NumberDecimal("1000.55")

The NumberDecimal() constructor also accepts double values from the mongo shell (i.e. without quotes), although this is not recommended due to the risk of losing precision. NumberDecimal()构造函数也接受来自mongo shell的双值(即不带引号),尽管不建议这样做,因为这样可能会丢失精度。The constructor creates a binary-based double precision representation of the decimal-based parameter (potentially losing precision), then converts that value to a decimal value with a precision of 15 digits. 构造函数创建基于十进制的参数的基于二进制的双精度表示(可能会丢失精度),然后将该值转换为精度为15位的十进制值。The following example passes the value implicitly as a double and shows how it is created with a precision of 15 digits:以下示例以double隐式传递值,并显示如何创建精度为15位的值:

NumberDecimal(1000.55)

The value is stored in the database as follows:该值存储在数据库中,如下所示:

NumberDecimal("1000.55000000000")

The following example passes the value implicitly as a double and shows how a loss of precision can occur:以下示例以double隐式传递该值,并显示了如何发生精度损失:

NumberDecimal(9999999.4999999999)

The value is stored in the database as follows:该值存储在数据库中,如下所示:

NumberDecimal("9999999.50000000")

Note

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

Equality and Sort Order相等和排序顺序

Values of the decimal type are compared and sorted with other numeric types based on their actual numeric value. decimal类型的值将根据其实际数值与其他数值类型进行比较和排序。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, so use the NumberDecimal() constructor when checking the equality of decimal values. 基于二进制的双精度类型的数值通常具有基于十进制值的近似表示形式,并且可能不完全等于其十进制表示形式,因此在检查十进制值的相等性时,请使用NumberDecimal()构造函数。Consider the following examples with the following documents in the numbers collection:请细看下面的示例,带有以下文档,形式为numbers集合:

{ "_id" : 1, "val" : NumberDecimal( "9.99" ), "description" : "Decimal" }
{ "_id" : 2, "val" : 9.99, "description" : "Double" }
{ "_id" : 3, "val" : 10, "description" : "Double" }
{ "_id" : 4, "val" : NumberLong("10"), "description" : "Long" }
{ "_id" : 5, "val" : NumberDecimal( "10.0" ), "description" : "Decimal" }

When the queries from the table below are plugged into the db.numbers.find(<query>) method, the following results are returned:将下表中的查询插入db.numbers.find(<query>)方法时,将返回以下结果:

Query查询Results结果
{ “val”: 9.99 } { “_id”: 2, “val”: 9.99, “description”: “Double” }
{ “val”: NumberDecimal( “9.99” ) } { “_id”: 1, “val”: NumberDecimal( “9.99” ), “description”: “Decimal” }
{ val: 10 }
{ “_id”: 3, “val”: 10, “description”: “Double” }
{ “_id”: 4, “val”: NumberLong(10), “description”: “Long” }
{ “_id”: 5, “val”: NumberDecimal( “10.0” ), “description”: “Decimal” }
{ val: NumberDecimal( “10” ) }
{ “_id”: 3, “val”: 10, “description”: “Double” }
{ “_id”: 4, “val”: NumberLong(10), “description”: “Long” }
{ “_id”: 5, “val”: NumberDecimal( “10.0” ), “description”: “Decimal” }

The first query, { "val": 9.99 }, implicitly searches for the double representation of 9.99 which is not equal to the decimal representation of the value.第一个查询{ "val": 9.99 }隐式搜索9.99的双精度表示,它不等于值的十进制表示。

The NumberDecimal() constructor is used to query for the document with the decimal representation of 9.99. NumberDecimal()构造函数用于查询十进制表示为9.99的文档。Values of the double type are excluded because they do not match the exact value of the decimal representation of 9.99.排除双精度类型的值,因为它们与十进制表示法9.99的精确值不匹配。

Matching values of all numeric types are returned when querying for whole numbers. 查询整数时返回所有数字类型的匹配值。For example, querying for a double representation of 10 will include a decimal representation of 10.0 in the results and vice versa.例如,查询10的双精度表示将在结果中包含10.0的十进制表示,反之亦然。

Checking for decimal Type检查十进制类型

To test for decimal type, use the $type operator with the string alias "decimal" or 19, the numeric code for the decimal type.要测试十进制类型,请使用带字符串别名"decimal"或十进制类型的数字代码19$type运算符。

db.inventory.find( { price: { $type: "decimal" } } )

Check Types in the mongo Shell检查mongo Shell中的类型

To determine the type of fields, the mongo shell provides the instanceof and typeof operators.为了确定字段的类型,mongo shell提供instanceof和typeof操作符。

instanceof

instanceof returns a boolean to test if a value is an instance of some type.instanceof返回一个布尔值,以测试值是否为某种类型的实例。

For example, the following operation tests whether the _id field is an instance of type ObjectId:例如,以下操作测试_id字段是否为ObjectId类型的实例:

mydoc._id instanceof ObjectId

The operation returns true.该操作返回true

typeof

typeof returns the type of a field.返回字段的类型。

For example, the following operation returns the type of the _id field:例如,以下操作返回_id字段的类型:

typeof mydoc._id

In this case typeof will return the more generic object type rather than ObjectId type.在这种情况下,typeof将返回更通用的object类型,而不是ObjectId类型。