The Data Types in MongoDB

Introduction

This article will be an introduction to the main data types in MongoDB with code examples to demonstrate each one.

Along with XML, JSON(JavaScript Object Notation) is the main format of data interchange used in modern web development. NoSQL databases like MongoDB use JSON to store records. JSON supports all the basic data types like number, string, char, boolean, etc. JSON is represented by MongoDB in a binary coded format known as Binary encoded JSON(BSON). BSON provides additional data types for the JSON model. MongoDB supports all BSON data types. 

Different types of MongoDB data type

String

The string is the most commonly used MongoDB data type. Strings in BSON are UTF-8. Any value written inside double quotes in JSON representation is a string value. Like in the following example, Peter is the value assigned to the name field.

> db.datatypes.insert({name: "Peter"})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{ "_id" : ObjectId("5d35e069956ce18f101ef12d"), "name" : "Peter" }
>

Integer

The integer is one of the basic data types used in every programming language. It is used to store an integer value. Two forms of this data type are present in Mongodb, 32 bits, and 64 bits. In the following JSON representation, the age field has an integer value.

> db.datatypes.insert({age: 21})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{ "_id" : ObjectId("5d35e160956ce18f101ef12e"), "age" : 21 }
>

Double

While the Integer data type only stores an integer value, Double data type is used to store a floating-point value.

> db.datatypes.insert({marks: 94.5})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{ "_id" : ObjectId("5d35e194956ce18f101ef12f"), "marks" : 94.5 }
>

Object

If a key-value pair is inserted inside another document, it is known as an embedded document. The object data type is used to store embedded documents. For example, In the following JSON representation, Address is an object data type.

> var address ={ street: "123 5th street", city: "New York", country: "USA"}
> db.datatypes.insert({name: "Peter", address: address})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{ "_id" : ObjectId("5d35e194956ce18f101ef12f"), "marks" : 94.5 }
{
        "_id" : ObjectId("5d35e1fb956ce18f101ef130"),
        "name" : "Peter",
        "address" : {
                "street" : "123 5th street",
                "city" : "New York",
                "country" : "USA"
        }
}
>

Boolean

Boolean data types stores boolean values. In the following example, Both the fields are of the Boolean data type.

> db.datatypes.insert({member: true, primemember: false})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{
        "_id" : ObjectId("5d35e22f956ce18f101ef131"),
        "member" : true,
        "primemember" : false
}
>

Note: boolean values are not written inside double-quotes.

Date

Date data type stores the current date or time. There are methods used to return date. Either it can be a string or date object. There are three such methods. 1. Date(), returns a string. 2. New Date(), return a date object. 3. ISODate(), also return a date object.

In the following representation, firstDate, secondDate, and thirdDate are created using Date(), New Date(), and ISODate() respectively.

> var date1 = Date()
> var date2 = new Date()
> var date3 = new ISODate()
> db.datatypes.insert({firstDate: date1, secondDate: date2, thirdDate: date3})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{
        "_id" : ObjectId("5d35e2c0956ce18f101ef132"),
        "firstDate" : "Mon Jul 22 2019 21:51:42 GMT+0530 (India Standard Time)",
        "secondDate" : ISODate("2019-07-22T16:21:48.099Z"),
        "thirdDate" : ISODate("2019-07-22T16:22:02.109Z")
}
>

Binary data

The binary data type is used to store Binary data.

> var data = BinData(1, "232sa3d323sd232a32sda3s2d3a2s1d23s21d3sa")
> db.datatypes.insert({binaryData: data})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{
        "_id" : ObjectId("5d35e347956ce18f101ef133"),
        "binaryData" : BinData(1,"232sa3d323sd232a32sda3s2d3a2s1d23s21d3sa")
}
>

Array

Arrays are stored in these data types. Arrays contain a set of values. Values inside the array can be of any data type. The value inside an array is enclosed in double brackets. For example, the Favbooks field is an array data type that contains multiple values.

> var favBooks = ["A game of thrones", "A clash of kings", "A sword of storms"]
> db.datatypes.insert({favBooks: favBooks})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{
        "_id" : ObjectId("5d35e39d956ce18f101ef134"),
        "favBooks" : [
                "A game of thrones",
                "A clash of kings",
                "A sword of storms"
        ]
}
>

JavaScript

To store a JavaScript code without a scope, JavaScript data type is used.

> db.datatypes.insert({JSCode: "function(){x=2+2}"})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{
        "_id" : ObjectId("5d35e3df956ce18f101ef135"),
        "JSCode" : "function(){x=2+2}"
}
>

Timestamp

A sequence of characters used to describe the date and time when an event has occurred is known as Timestamp. Timestamp data type store such characters. new Timestamp() is used to create a timestamp.

> var timestamp = new Timestamp()
> db.datatypes.insert({timestamp: timestamp})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{
        "_id" : ObjectId("5d35e44b956ce18f101ef136"),
        "timestamp" : Timestamp(1563812939, 1)
}
>

Regular Expression

This data type stores regular expression. It is similar to JavaScript’s regular expression.

> var regex = new RegExp("%mongodb%")
> db.datatypes.insert({regular: regex})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{ "_id" : ObjectId("5d35e49c956ce18f101ef137"), "regular" : /%mongodb%/ }
>

Null

Null values can also be stored in MongoDB. The null data type is used for this.

> db.datatypes.insert({value: null})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{ "_id" : ObjectId("5d35e4d2956ce18f101ef138"), "value" : null }
>

Undefined

Undefined values are stored in MongoDB using this data type. But this data type is being deprecated.

> db.datatypes.insert({value: undefined})
WriteResult({ "nInserted" : 1 })
> db.datatypes.find().pretty()
{ "_id" : ObjectId("5d35e4f6956ce18f101ef139"), "value" : undefined }
>

ObjectId

Observe all the above examples. There is a field name _id. It is created every time automatically when a document is created. Every document created in MongoDB has a default id field names as _id. It contains a unique value for every document.

Conclusion

These were the major data types used in MongoDB. Apart from these, there are few more data types like min key which compares with the least BSON element, the max key which compares with the highest BSON element, Javascript with scope, 32-bit integer, and 64-bit integer. Data types play an important part in MongoDB. BSON supports more data types and these data types are useful while creating MongoDB documents.

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.