MongoDB Data Types Tutorial with Examples

By Digamber Rawat Last updated on
In this tutorial, we are going to talk about MongoDB data types and their usage. If you are trying your hand first time in MongoDB, then i would suggest you should go through the following MongoDB tutorials.

Series Tutorial
1 Install MongoDB on MacOS in 5 Minutes
2 Install MongoDB on Windows
3 MongoDB Create A Collection
4 MongoDB Drop a Collection
5 MongoDB Remove a Collection
6 Uninstall MongoDB from Ubuntu

MongoDB uses the BSON serialization format to store the data on the disk. BSON is a short form of Binary-encoded format of JSON, and BSON helps in making the remote procedure calls. When we talk about data types in MongoDB, MongoDB supports a wide array of data types to examine a document in the data collection. MongoDB supports BSON serialization because it supports more data types than the JSON format.

MongoDB helps in translating between BSON and the language associated documents representation.

In MongoDB, every data type has a related numerical value from 1 to 255, and it is used by `$type` operator to search through the collection.

You can find out more details on BSON here at http://bsonspec.org

MongoDB Data Types with Numerical Identifiers

Check out data types with their corresponding identifiers in the table below:

Data Type ID Number
Double 1
String 2
Object 3
Array 4
Binary Data 5
Undefined 6
Object Id 7
Boolean 9
Date 10
Null 11
Regular Expression 12
JavaScript 13
Symbol 14
JavaScript with scope 15
Integer 16 and 18
Timestamp 10
Min Key 255
Max Key 127

Data Types in MongoDB Examples

In the given below example you can find out data types with examples:

Double

This data type is used to store the floating point value in MongoDB.

> var double = 2345.54
> double

# 2345.54

String

This data type is used to store the valid BSON strings in UTF-8 format, in the given below example we are inserting a valid string in a mongoDB document.

> db 
angular8mean
> use angular8mean
switched to db angular8mean
> db.angular8mean.insert({Document: "MongoDB data type"})
WriteResult({ "nInserted" : 1 })
> db.angular8mean.find()
{ "_id" : ObjectId("5d0f4eed01e668ef2b2651c4"), "Document" : "MongoDB data type" }

Object

An object data type is used to store the embedded document. A series of nested document, especially in `key: value` pair format, is known as an embedded document.

As you can see in the example below, we are inserting a document by the name of local in `angular8mean` database. This is an object data type example.

> var local = {author: "Digamber", score: 5.5, publication: "positronx"}
> db.angular8mean.insert({system: "MacOS", diskspace: "10GB", server:local})
WriteResult({ "nInserted" : 1 })
> db.angular8mean.find().pretty()
{
        "_id" : ObjectId("5d0f4eed01e668ef2b2651c4"),
        "Document" : "MongoDB data type"
}
{
        "_id" : ObjectId("5d0f50f701e668ef2b2651c5"),
        "system" : "MacOS",
        "diskspace" : "10GB",
        "server" : {
                "author" : "Digamber",
                "score" : 5.5,
                "publication" : "positronx"
        }
}

Array

This data type helps in storing the array, we can store multiple values or a list in one item. Let’s find out In the below example, how to store values in an array.

> db
angular8mean
> use angular8mean
switched to db angular8mean
> var array1 = ['USA', 'France', 'UK']
> var array2 = ['USA', 'France', 'UK', 515, 615, 2.15]
> var array3 = ['USA', 'France', 'UK', 515, new Date()]
> db.angular8mean.insert({data1: array1, data2: array2, data3: array3})
WriteResult({ "nInserted" : 1 })
> db.angular8mean.find().pretty()
{
        "_id" : ObjectId("5d0f539401e668ef2b2651c6"),
        "data1" : [
                "USA",
                "France",
                "UK"
        ],
        "data2" : [
                "USA",
                "France",
                "UK",
                515,
                615,
                2.15
        ],
        "data3" : [
                "USA",
                "France",
                "UK",
                515,
                ISODate("2019-06-23T10:24:11.326Z")
        ]
}

Binary Data

This MongoDB data type helps in storing binary data.

Undefined

This data type in MongoDB stores the undefined values:

db.angular8mean.insert({system: "MacOS", diskspace: "10GB", server:undefined})
WriteResult({ "nInserted" : 1 })
> db.angular8mean.find().pretty()
{
        "_id" : ObjectId("5d0f57b501e668ef2b2651c7"),
        "system" : "MacOS",
        "diskspace" : "10GB",
        "server" : undefined
}

ObjectId

This data type in MongoDB stores the unique document’s ID, MongoDB offers an_id field for every document. MongoDB’s ObjectId size is 12 bytes and it is divided into four parts: Timestamp, Machine id, Counter and Process id

> var id = ObjectId()
> db.angular8mean.insert({_id:id, name: "Avenger"})
WriteResult({ "nInserted" : 1 })
> db.angular8mean.find().pretty()

{ "_id" : ObjectId("5d0f595601e668ef2b2651cb"), "name" : "Avenger" }

Boolean

This data type helps in storing the Boolean values:

> db.newdatabase.insert({_id: ObjectId(), yes: true, no: false})
WriteResult({ "nInserted" : 1 })
> db.newdatabase.find().pretty()
{ "_id" : ObjectId("5d0f5a4201e668ef2b2651cc"), "yes" : true, "no" : false }

Date

The date data type in MongoDB stores the current date/time in UNIX time format. It also allows you to create your own date by declaring a date object.

> var date1 = new Date()
> var date2 = ISODate()
> var date3 = Date()
> db.datedb.insert({_id: ObjectId(), Date1: date1, Date2: date2, Date3: date3})
WriteResult({ "nInserted" : 1 })
> db.datedb.find().pretty()
{
        "_id" : ObjectId("5d0f5c7e01e668ef2b2651ce"),
        "Date1" : ISODate("2019-06-23T11:03:11.704Z"),
        "Date2" : ISODate("2019-06-23T11:03:16.962Z"),
}

Null

This data type in MongoDB is used to store a null value:

> db.positron1.insert({Name: "John", value: null})
WriteResult({ "nInserted" : 1 })
> db.positron1.find().pretty()
{
        "_id" : ObjectId("5d0f5daa01e668ef2b2651cf"),
        "Name" : "John",
        "value" : null
}

Regular Expression

This data type helps in storing the regular expressions in MongoDB. It is similar to JavaScript regular expression.

JavaScript

These MongoDB data types allow us to store the JavaScript data without a scope.

> db.positron2.insert({val: 18, method: "function(){x 2; y+2}",scope:{}})
WriteResult({ "nInserted" : 1 })
> db.positron2.find().pretty()
{
        "_id" : ObjectId("5d0f621801e668ef2b2651d0"),
        "val" : 18,
        "method" : "function(){x 2; y+2}",
        "scope" : { }
}

Symbol

This data type is similar to a string, MongoDB shell doesn’t support by a shell symbol. However, if the shell receives a symbol from the database, it is covert it into a strings.

JavaScript with Scope

This data type in MongoDB allows us to store JavaScript data with a scope.

> db.positron3.insert({number: 28, method: "function(){x 2; y+2}",scope:["DataObject"]})
WriteResult({ "nInserted" : 1 })
> db.positron3.find().pretty()
{
        "_id" : ObjectId("5d0f63b501e668ef2b2651d1"),
        "number" : 28,
        "method" : "function(){x 2; y+2}",
        "scope" : [
                "DataObject"
        ]
}

Integer

This data type helps in storing the numerical value, and it supports 32 bits and 64 bits data type:

> var maths = 50
> db.positron4.insert({name: "Digamber", numbers: maths})
WriteResult({ "nInserted" : 1 })
> db.positron4.find().pretty()
{
        "_id" : ObjectId("5d0f647c01e668ef2b2651d2"),
        "name" : "Digamber",
        "numbers" : 50
}

Timestamp

The Timestamp data type is used to store a timestamp in MongoDB.

> var timestamp = new Timestamp()
> timestamp
Timestamp(0, 0)
> db.positronx5.insert({_id: 599, TimeStamp: timestamp})
WriteResult({ "nInserted" : 1 })
> db.positronx5.find().pretty()
{ "_id" : 599, "TimeStamp" : Timestamp(1561290091, 1) }

As you can see the initial value of the timestamp is (0,0), and when we ran the command, it became (1561290091, 1). The first value is the timestamp, and the second value refers to the order of operation.

Min/ Max keys

The Timestamp data type is used to store a timestamp in MongoDB.
The Min/Max keys allow us to check the value corresponding to the lowest and the highest BSON items.

Conclusion

We have highlighted the widely used MongoDB Data Types in this tutorial. We also tried to understand about BSON serialization format and it’s role in MongoDB. I hope this tutorial will help you to understand the MongoDB operation a bit more. If you loved this article, then don’t forget to share it with others.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.