Data Types in the mongo Shell

MongoDB BSON provides support for additional data types thanJSON. Drivers provide nativesupport for these data types in host languages and themongo shell also provides several helper classes to supportthe use of these data types in the mongo JavaScriptshell. See the Extended JSONreference 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 theISODate() wrapper.
  • ISODate() constructor which returns a Date object using theISODate() wrapper.

Internally, Date objects are stored as a signed64-bit integer representing the number of milliseconds since the Unixepoch (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 range0 through 9999.

Return Date as a String

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

  1. var myDateString = Date();

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

  1. myDateString

The result is the value of myDateString:

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

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

  1. typeof myDateString

The operation returns string.

Return Date

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

The following example uses both the new Date() constructor and theISODate() constructor to return Date objects.

  1. var myDate = new Date();
  2. var myDateInitUsingISODateWrapper = ISODate();

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

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

  1. myDate

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

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

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

  1. myDate instanceof Date
  2. myDateInitUsingISODateWrapper instanceof Date

The operation returns true for both.

ObjectId

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

  1. new ObjectId

See

ObjectId

NumberLong

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

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

  1. NumberLong("2090845886852")

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

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

Retrieve the document to verify:

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

In the returned document, the calc field contains aNumberLong object:

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

If you use the $inc to increment the value of a field thatcontains a NumberLong object by a float, the data type changesto a floating point value, as in the following example:

  • Use $inc to increment the calc field by 5, which themongo shell treats as a float:
  1. db.collection.updateOne( { _id: 10 },
  2. { $inc: { calc: 5 } } )
  • Retrieve the updated document:
  1. db.collection.findOne( { _id: 10 } )

In the updated document, the calc field contains a floatingpoint value:

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

NumberInt

The mongo shell treats all numbers as floating-point valuesby 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-pointdouble values by default. The mongo shell provides theNumberDecimal() constructor to explicitly specify 128-bitdecimal-based floating-point values capable of emulating decimalrounding with exact precision. This functionality is intended forapplications that handlemonetary data, such asfinancial, tax, and scientific computations.

The decimal BSON typeuses the IEEE 754 decimal128 floating-point numbering format whichsupports 34 decimal digits (i.e. significant digits) and an exponentrange of −6143 to +6144.

The NumberDecimal() constructor accepts the decimal value as astring:

  1. NumberDecimal("1000.55")

The value is stored in the database as follows:

  1. NumberDecimal("1000.55")

The NumberDecimal() constructor also accepts double values fromthe mongo shell (i.e. without quotes), although this is notrecommended due to the risk of losing precision. The constructorcreates a binary-based double precision representation of thedecimal-based parameter (potentially losing precision), thenconverts that value to a decimal value with a precision of 15digits. The following example passes the value implicitly as adouble and shows how it is created with a precision of 15 digits:

  1. NumberDecimal(1000.55)

The value is stored in the database as follows:

  1. NumberDecimal("1000.55000000000")

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

  1. NumberDecimal(9999999.4999999999)

The value is stored in the database as follows:

  1. NumberDecimal("9999999.50000000")

Note

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

Equality and Sort Order

Values of the decimal type are compared and sorted with othernumeric types based on their actual numeric value. Numeric valuesof the binary-based double type generally have approximaterepresentations of decimal-based values and may not be exactlyequal to their decimal representations, so use theNumberDecimal() constructor when checking the equality ofdecimal values. Consider the following examples with the followingdocuments in the numbers collection:

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

When the queries from the table below are plugged into thedb.numbers.find(<query>) method, the following results arereturned:

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 thedouble representation of 9.99 which is not equal to thedecimal representation of the value.

The NumberDecimal() constructor is used to query for the documentwith the decimal representation of 9.99. Values of thedouble type are excluded because they do not match the exact valueof the decimal representation of 9.99.

Matching values of all numeric types are returned when querying forwhole numbers. For example, querying for a double representation of10 will include a decimal representation of 10.0 in theresults and vice versa.

Checking for decimal Type

To test for decimal type, use the $type operator with thestring alias "decimal" or 19, the numeric code for thedecimal type.

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

Check Types in the mongo Shell

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

instanceof

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

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

  1. 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 _idfield:

  1. typeof mydoc._id

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