Data Types in the mongo Shell

On this page

MongoDB BSON provides support for additional data types than JSONDrivers 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. See the Extended JSON reference for additional information.

Types

Date

The mongo shell provides various methods to return the date, either as a string or as a Date object:

  • Date() method which returns the current date as a string.
  • new Date() constructor which returns a Date object using the ISODate() wrapper.
  • ISODate() constructor which returns a Date object using the ISODate() wrapper.

Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

Not all database operations and drivers support the full 64-bit range. You may safely work with dates with years within the inclusive range 0 through 9999.

Return Date as a String

To return the date as a string, use the Date() method, as in the following example:

copy

copied

var myDateString = Date();

To print the value of the variable, type the variable name in the shell, as in the following:

copy

copied

myDateString

The result is the value of myDateString:

copy

copied

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

To verify the type, use the typeof operator, as in the following:

copy

copied

typeof myDateString

The operation returns string.

Return Date

The mongo shell wraps objects of Date type with the ISODate helper; however, the objects remain of type Date.

The following example uses both the new Date() constructor and the ISODate() constructor to return Dateobjects.

copy

copied

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

You can use the new operator with the ISODate() constructor as well.

To print the value of the variable, type the variable name in the shell, as in the following:

copy

copied

myDate

The result is the Date value of myDate wrapped in the ISODate() helper:

copy

copied

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

To verify the type, use the instanceof operator, as in the following:

copy

copied

myDate instanceof Date
myDateInitUsingISODateWrapper instanceof Date

The operation returns true for both.

ObjectId

The mongo shell provides the ObjectId() wrapper class around the ObjectId data type. To generate a new ObjectId, use the following operation in the mongo shell:

copy

copied

new ObjectId

SEE

ObjectId

NumberLong

The mongo shell treats all numbers as floating-point values by default. The mongo shell provides the NumberLong() wrapper to handle 64-bit integers.

The NumberLong() wrapper accepts the long as a string:

copy

copied

NumberLong("2090845886852")

The following examples use the NumberLong() wrapper to write to the collection:

copy

copied

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:

copy

copied

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

In the returned document, the calc field contains a NumberLong object:

copy

copied

{ "_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:

  1. Use $inc to increment the calc field by 5, which the mongo shell treats as a float:

    copy

    copied

    db.collection.updateOne( { _id: 10 },
                          { $inc: { calc: 5 } } )
    
  2. Retrieve the updated document:

    copy

    copied

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

    In the updated document, the calc field contains a floating point value:

    copy

    copied

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

NumberInt

The mongo shell treats all numbers as floating-point values by default. The mongo shell provides the NumberInt() constructor to explicitly specify 32-bit integers.

NumberDecimal

New in version 3.4.

The mongo shell treats all numbers as 64-bit floating-point double values by default. 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. This functionality is intended for applications that handlemonetary 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.

The NumberDecimal() constructor accepts the decimal value as a string:

copy

copied

NumberDecimal("1000.55")

The value is stored in the database as follows:

copy

copied

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. 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. The following example passes the value implicitly as adouble and shows how it is created with a precision of 15 digits:

copy

copied

NumberDecimal(1000.55)

The value is stored in the database as follows:

copy

copied

NumberDecimal("1000.55000000000")

The following example passes the value implicitly as a double and shows how a loss of precision can occur:

copy

copied

NumberDecimal(9999999.4999999999)

The value is stored in the database as follows:

copy

copied

NumberDecimal("9999999.50000000")

NOTE

To use the decimal data type with a MongoDB driver, be sure to use a driver version that supports it.

Equality and Sort Order

Values of the decimal type are compared and sorted with other numeric types based on their actual numeric value. 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. Consider the following examples with the following documents in the numbers collection:

copy

copied

{ "_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:

QueryResults
{ “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.

The NumberDecimal() constructor is used to query for the document with the decimal representation of 9.99. Values of the double type are excluded because they do not match the exact value of the decimalrepresentation of 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.

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.

copy

copied

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

Check Types in the mongo Shell

To determine the type of fields, the mongo shell provides the instanceof and typeof operators.

instanceof

instanceof returns a boolean to test if a value is an instance of some type.

For example, the following operation tests whether the _id field is an instance of type ObjectId:

copy

copied

mydoc._id instanceof ObjectId

The operation returns true.

typeof

typeof returns the type of a field.

For example, the following operation returns the type of the _id field:

copy

copied

typeof mydoc._id

In this case typeof will return the more generic object type rather than ObjectId type.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值