MongoDB is one of the most popular NoSQL database management systems (DBMS) these days. There are many reasons behind its popularity, including flexibility, scalability, performance, and agility. It uses BSON format to store data, which gives individuals the ability to use different data types.
It is very important to understand how one should use these data types to get the most out of them. This blog post includes everything around it. It contains many of the most popular data types along with examples of their use. Let's get started.
Understanding what are data types in MongoDB means recognising how many data types we can use on this tool. There are many options in this case, as it can use almost every popular one. Each of them has its own set of rules and properties. Individuals should be aware of these in order to control and manipulate these databases efficiently.
For instance, integers like dates are stored as 64-bit. This information makes experts understand which type of information they can use for a particular task. This is how they can design efficient database schemas, perform complicated queries and ensure information integrity.
Explore igmGuru's Big Data Certification Courses to enhance your skills.
The following are the most popular data types in MongoDB -
Integers contain all numerical values without decimals like age. It stores data in two formats, including 32 and 64-bit. The choice of the format depends on the server type.
db.student.insertOne({name:"Akash",age:19}) { "acknowledged" : true, "insertedId" : ObjectId("601af3456fd54aa34c9c6df5") } db.student.find().pretty() { "_id" : ObjectId("601af2dd6fd54aa34c9c6df3"), "name" : "Akshay" } { "_id" : ObjectId("601af2dd6fd54aa34c9c6df4"), "name" : "Vikash" } { "_id" : ObjectId("601af3456fd54aa34c9c6df5"), "name" : "Akash", "age" : 19 } |
This is one of the most common UTF-8 data types in MongoDB. It stores information in string format, which is manipulated by the programming language into UTF-8 format. One can use it to store any name in a collection as given below.
switched to db gfg db.student.insertMany([{name:"Akshay"},{name:"Vikash"}]) { "acknowledged" : true, "insertedIds" : [ ObjectId("601af2dd6fd54aa34c9c6df3"), ObjectId("601af2dd6fd54aa34c9c6df4") ] } db.student.find().pretty() { "_id" : ObjectId("601af2dd6fd54aa34c9c6df3"), "name" : "Akshay" } { "_id" : ObjectId("601af2dd6fd54aa34c9c6df4"), "name" : "Vikash" } |
This data type only stores Boolean values like true or false. It takes less space than the other ones, like integers and strings. This avoids the unwanted comparison effects. The following is an instance of using this data type.
db.interns.insertOne({ intern_name: "Tom Cruise", intern_skills: "Acting", intern_score: 87.75, intern_status: true }) |
Double data type stores floating values like decimal numbers. These numbers can be large but not precise every time. This means the input and output may not be the same each time. One can use it to represent the marks of a student on a test as shown below.
db.mytestcoll.insertOne({testScore: 89.6}) { "acknowledged": true, "insertedId": ObjectId("614b37296a124db40ae74d13") } |
The array is a combination of many similar or different types of values in a single document. This data type is used to store these documents. Here is an instance of its use case.
db.student.insertOne({ name: "Akash", skills: ["C", "C++", "Java", "Python", "JS"] }) |
Also Read- MongoDB Tutorial For Beginners
These data types store the embedded/nested documents. These are the documents that contain many other documents within itself. Think of it as a document that contains all the information about a book.
db.book.insertOne({Book:{name:"C in depth",writer:"Aaksh"}}) { "acknowledged" : true, "insertedId" : ObjectId("601af71f6fd54aa34c9c6df9") } db.book.find().pretty() { "_id" : ObjectId("601af71f6fd54aa34c9c6df9"), "Book" : { "name" : "C in depth", "writer" : "Aaksh" } } |
MongoDB automatically gives a unique ID to each document in case it does not have one. This ID stores information in hexadecimal format with a length of 12 bytes. This information consists of 4 bytes of Timestamp value, 5 bytes of random values, 3 bytes of machine ID, 2 bytes of process ID, and 3 bytes of counter.
db.book.insertOne({Book:{name:"C in depth",writer:"Akash"}}) { "acknowledged" : true, "insertedId" : ObjectId("601af71f6fd54aa34c9c6df9") } db.book.find().pretty() { "_id" : ObjectId("601af71f6fd54aa34c9c6df9"), "Book" : { "name" : "C in depth", "writer" : "Aaksh" } } |
The date data type in MongoDB stores date and time in the form of a 64-bit integer. It is very useful in querying and storing values like creation dates or timestamps. Think of it like an index that includes dates and times of blogs.
{ "_id": ObjectId("6156b35eb6a0221ebf2c1ec3"), "title": "My First Blog Post", "content": "Explore my website.", "created_at": ISODate("2021-10-01T12:00:00Z") } |
Symbol data type stores identifier values that are globally unique. Symbols represent an array of characters like strings, where their global uniqueness makes them different. Think of it as a table that contains the roles of each employee in a company. The Symbol data type is now deprecated in many MongoDB drivers and should generally be avoided in favor of using Strings.
{ "_id": ObjectId("6156b35eb6a0221ebf2c1ec2"), "name": "Jane Doe", "role": Symbol("admin") } |
Read Also- How to Create a Database in MongoDB
Code data type stores JavaScript programs as a string. These programs are intended to execute on the database server. One can use it in product listings where it can calculate the total quantity and the sum of prices of articles.
db.products.insertOne({ name: "Widget", price: 10, quantity: 5, total: new Code("function() { return this.price * this.quantity; }") }) |
This data type can store regular expressions referring to the value of a field. This tool uses PCRE (Perl Compatible Regular Expression) as its expression language. It is very useful in writing database objects with matching triggers or validation patterns.
db.mytestcoll.find().pretty() { _id: ObjectId("614b37296a124db40ae74d16"), exampleregex: /tt/ } { _id: ObjectId("614b37296a124db40ae74d17"), exampleregex: /t+/ } |
This type of data stores binary information as a field value. It is best for storing and searching any information. The instance given below stores binary information in a document of collection.
var data = BinData(1, "111010110111100110100010101") db.mytestcoll.insertOne({binaryData: data}) { "acknowledged": true, "insertedId": ObjectId("614b37296a124db40ae74d20") } db.mytestcoll.find().pretty() { "_id" : ObjectId("614b37296a124db40ae74d20"), "binaryData" : BinData(1, "111010110111100110100010101") } |
Knowing the data types discussed in this article covers many common use cases and helps lay a solid foundation for working with MongoDB. This article has already explained most of them but there are many more that can be used in different areas. Knowing the types in this article many most of the use cases. It gives a strong foundation to begin using this DBMS.
There are two methods by which one can check data types in MongoDB, including $type() and using the constructor. One can use a $type query operator that accepts a numeric code or a string alias of data type. The other one is using a constructor to determine the data type by analyzing the object.
ObjectID values are only 12 bytes in length, where strings are hexadecimal and contain a total of 24 bytes. ObjectID also has a more efficient index and is preferred over the string type.
BSON (Binary JavaScript Object Notation) is a binary serialization of JSON (JavaScript Object Notation) documents. It can use almost every type of data.
About Author
Course Schedule
| Course Name | Batch Type | Details |
| MongoDB Training | Every Weekday | View Details |
| MongoDB Training | Every Weekend | View Details |