MongoDB

What are the valid MongoDB datatypes

MongoDB is a widely used non-relational database management system. The data storing mechanism of MongoDB (or any other database) strongly relies on the data types supported by that database management system. MongoDB stores data in the form of BSON, which is a binary-encoded format of JSON as its name is also derived from “Binary” and “JSON”. The data types that BSON supports are considered valid for MongoDB.

This article of the MongoDB series will provide detailed information about the data types used in MongoDB. But before that, let’s have a comparison of JSON format and its binary extension BSON.

JSON vs. BSON

The JSON (JavaScript Object Notation) format is human readable and is mainly used for the transmission of data. The JSON type of data consists of key-value pairs (usually known as objects) and an array. The transmission in JSON depends on the key-value pairs. The JSON documents take less space, but the execution in JSON usually takes more time than BSON.

BSON is a binary extension of JSON that is machine-readable and is used for storing data. The data can be stored using BSON by specifying a field name(usually specified as a string) and then assigning it a value(can be any type supported by MongoDB) BSON consumes more space because it stores extra information as well (like the length of the string) but its execution is fast. Moreover, the number of data types supported by BSON is greater than JSON.

What are the data types supported by MongoDB?

This section contains the assignment of several data types to field values in MongoDB. An example for storing each data type is also provided.

Note: The collection name is “Authors,” and we have printed each document by using find with pretty methods in MongoDB. The find() method prints the result, where the pretty() method prints that result in an esthetically sound manner.

> db.Authors.find().pretty()

String: The string value can be stored to any field by representing it inside double quotes(” “). The following command will insert a document that contains a string field in the “Authors” collection:

> db.Authors.insertOne({Name: "Sam"})

Text Description automatically generated

Or you can also insert by creating a string variable first and then calling that variable into a MongoDB document.

Create a variable:

> var fname="Sam"

Logo Description automatically generated with medium confidence

Insert into a document:

> db.Authors.insertOne({Name: fname})

Text Description automatically generated

Integer : The integer (float values are not included) value can be inserted in MongoDB by the following way:

> db.Authors.insertOne({num: 10})

Text Description automatically generated

Arrays: A set of values can be stored in MongoDB using an array; this data type can store several fields that contain different data types:

> db.Authors.insertOne({staff: ["John", "Mike", "Jobes"]})

Text Description automatically generated

Boolean : These data types accept only Boolean value (True or False); the following command stores a Boolean value:

> db.Authors.insertOne({pass: true, fail: false})

Text Description automatically generated

Double: The double data type can be used to store floating values. An example to store a floating value in a MongoDB document is written below:

> db.Authors.insertOne({number: 12.25})

Text Description automatically generated

Object: The object data type is used to store an embedded document in a MongoDB document. The object data type accepts other data types in the form of key-value pairs. For this, we have created an object variable first, and then we will call it in to a MongoDB collection:

To create an object variable:

> var info={name: "Mark", age: 45, city: "NewYork"}

Graphical user interface Description automatically generated

Inserting it into another document:

> db.Authors.insertOne({distribution: "Ubuntu", Author: info})

Text Description automatically generated

Note: In object data type, the variable creation is not necessary, but it is recommended because sometimes complex documents may need extra time to string an object directly.

Undefined: This data type helps to store values that are undefined. For instance, you can store a field (to remember) whose value is not defined yet, and later you can replace it. The following command helps to store an undefined value to field in a document:

> db.Authors.insertOne({period: undefined})

Text Description automatically generated

ObjectId : Every database stores data with a unique identification number. In MongoDB, the ObjectId() can be used to assign a unique id to the document by using the below mentioned command:

> db.Authors.insertOne({_id: ObjectId()})

Text Description automatically generated

Note: If you forgot to assign a unique id to a document, then MongoDB automatically assigns it.

Date: This data type can be used to store the current date and time. Moreover, this data type has the following extensions:

Date(): This type of Date will return the answer in string format. And it can be declared by following way:

> db.Authors.insertOne({date: Date()})

Text Description automatically generated

ISODate(): This type returns a date object, and it uses the ISO date wrapper to display the field.

> db.Authors.insertOne({date: ISODate()})

Text Description automatically generated

Timestamp: This data type can be used to put a timestamp in a document which is very useful especially when you keep on updating databases regularly. The example to put Timestamp is given below:

> db.Authors.insertOne({ts: new Timestamp()})

Text Description automatically generated

Min and Max key : The MinKey and MaxKey compare the minimum and maximum values in the BSON element. These types are referred as internal data types:

> db.Authors.insert([{t:5},{t: null},{t:15},{t:25},{t:MinKey},{t:MaxKey}])

Text Description automatically generated

Symbol: The symbol data type is not recognized by the MongoDB shell, and thus it is considered as a string data type. The assignment of a Symbol is the same as that of a string data type:

> db.Authors.insertOne([{designation: "#$%author$#@"}])

Text Description automatically generated

Null: This data type can be used to assign a null value in a field of a document. The following example will help to assign a null value to a field:

> db.Authors.insertOne({value: null})

Text Description automatically generated with medium confidence

Regular Expression: The regular expressions can be stored with the help of this data type. For instance, here, we have created a variable that stores a regular expression “^linux“.

To store a regular expression in a variable:

> var re= new RegExp("^linux")

A picture containing text Description automatically generated

And now the variable is called to store it in a document:

> db.Authors.insertOne({regex: re})

Text Description automatically generated

Note: The regular expressions can be super useful in searching a piece of string from several fields in a collection.

Conclusion

The data type support plays a key role in processing data inside any Database Management system. MongoDB supports all types that fall under the umbrella of the BSON type. In this article of the MongoDB series, we have compiled a list of valid data types in MongoDB. Moreover, each data type is described, and an example is quoted for better understanding as well. If you have used MongoDB or plan to use it in the future, this post would be beneficial for you to get a birds-eye view of data types in MongoDB.

About the author

Adnan Shabbir