Home Data MongoDB Fundamentals

MongoDB Fundamentals

By Amit Phaltankar , Juned Ahsan , Michael Harrison and 1 more
books-svg-icon Book
eBook $29.99 $20.98
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    2. Documents and Data Types
About this book
MongoDB is one of the most popular database technologies for handling large collections of data. This book will help MongoDB beginners develop the knowledge and skills to create databases and process data efficiently. Unlike other MongoDB books, MongoDB Fundamentals dives into cloud computing from the very start – showing you how to get started with Atlas in the first chapter. You will discover how to modify existing data, add new data into a database, and handle complex queries by creating aggregation pipelines. As you progress, you'll learn about the MongoDB replication architecture and configure a simple cluster. You will also get to grips with user authentication, as well as techniques for backing up and restoring data. Finally, you'll perform data visualization using MongoDB Charts. You will work on realistic projects that are presented as bitesize exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way. Many of these mini-projects are based around a movie database case study, while the last chapter acts as a final project where you will use MongoDB to solve a real-world problem based on a bike-sharing app. By the end of this book, you'll have the skills and confidence to process large volumes of data and tackle your own projects using MongoDB.
Publication date:
December 2020
Publisher
Packt
Pages
748
ISBN
9781839210648

 

2. Documents and Data Types

Overview

This chapter introduces you to MongoDB documents, their structure, and data types. For those who are new to the JSON model, this chapter will also serve as a short introduction to JSON. You will identify the basic concepts and data types of JSON documents and compare the document-based storage of MongoDB with the tabular storage of relational databases. You will learn how to represent complex data structures in MongoDB using embedded objects and arrays. By the end of this chapter, you will understand the need for precautionary limits and restrictions on MongoDB documents.

 

Introduction

In the previous chapter, we learned how MongoDB, as a NoSQL database, differs from traditional relational databases. We covered the basic features of MongoDB, including its architecture, its different versions, and MongoDB Atlas.

MongoDB is designed for modern-world applications. We live in a world where requirements change rapidly. We want to build lightweight and flexible applications that can quickly adapt to these new requirements and ship them to production as quickly as possible. We want our databases to become agile so that they can adapt to the ever-changing needs of our applications, reduce downtime, scale out easily, and perform efficiently. MongoDB is a perfect fit for all such needs.

One of the major factors that make MongoDB an agile database is its document-based data model. Documents are widely accepted as a flexible way of transporting information. You might have come across many applications that exchange data in the form of JavaScript Object Notation...

 

Introduction to JSON

JSON is a full-text, lightweight format for data representation and transportation. JavaScript's simple representation of objects gave birth to JSON. Douglas Crockford, who was one of the developers of the JavaScript language, came up with the proposal for the JSON specification that defines the grammar and data types for the JSON syntax.

The JSON specification became a standard in 2013. If you have been developing applications for a while, you might have seen the transition of applications from XML to JSON. JSON offers a human-readable, plain-text way of representing data. In comparison to XML, where information is wrapped inside tags, and lots of tags make it look bulky, JSON offers a compact and natural format where you can easily focus on the information.

To read or write information in JSON or XML format, the programming languages use their respective parsers. As XML documents are bound by schema definitions and tag library definitions...

 

BSON

When you work with MongoDB using database clients such as mongo shell, MongoDB Compass, or the Collections Browser in Mongo Atlas, you always see the documents in human readable JSON format. However, internally, MongoDB documents are stored in a binary format called BSON. BSON documents are not human-readable, and you will never have to deal with them directly. Before we explore MongoDB documents in detail, let's have a quick overview of the BSON features that benefit the MongoDB document structure.

Like JSON, BSON was introduced in 2009 by MongoDB. Although it was invented by MongoDB, many other systems also use it as a format for data storage or transportation. BSON specifications are primarily based on JSON as they inherit all the good features of JSON, such as the syntax and flexibility. It also provides a few additional features, which are specifically designed for improving storage efficiency, ease of traversal, and a few data type enhancements to avoid the type...

 

MongoDB Documents

A MongoDB database is composed of collections and documents. A database can have one or more collections, and each collection can store one or more related BSON documents. In comparison to RDBMS, collections are analogous to tables and documents are analogous to rows within a table. However, documents are much more flexible compared with the rows in a table.

RDBMSes consist of a tabular data model that comprises rows and columns. However, your applications may need to support more complex data structures, such as a nested object or a collection of objects. Tabular databases restrict the storage of such complex data structures. In such cases, you will have to split your data into multiple tables and change the application's object structures accordingly. On the other hand, the document-based data model of MongoDB allows your application to store and retrieve more complex object structures due to the flexible JSON-like format of the documents.

The following...

 

MongoDB Data Types

You have learned how MongoDB stores JSON-like documents. You have also seen various documents and read the information stored within them and seen how flexible these documents are to store different types of data structures, irrespective of the complexity of your data.

In this section, you will learn about the various data types supported by MongoDB's BSON documents. Using the right data types in your documents is very important as correct data types help you use the database features more effectively, avoid data corruption, and improve data usability. MongoDB supports all the data types from JSON and BSON. Let's look at each in detail, with examples.

Strings

A string is a basic data type used to represent text-based fields in a document. It is a plain sequence of characters. In MongoDB, the string fields are UTF-8 encoded, and thus they support most international characters. The MongoDB drivers for various programming languages convert the string...

 

Limits and Restrictions on Documents

So far, we have discussed the importance and benefits of using documents. Documents play a major role in building efficient applications, and they improve overall data usability. We know how documents offer a flexible way to represent data in its most natural form. They are often self-contained and can hold a complete unit of information. The self-containment comes from nested objects and arrays.

To use any database effectively, it is important to have the correct data structure. The incorrect data structures you build today may result in lots of pain in the future. In the long term, as your application's usage grows, the amount of data also grows, and the problems that seemed very small initially become more evident. Then comes the obvious question: how do you know whether your data structure is correct?

Your application will tell you the answer. If, to access a certain piece of information, your application must execute multiple queries...

 

Field Name Rules

MongoDB has a few rules about document field names, which are listed as follows:

  1. The field name cannot contain a null character.
  2. Only the fields in an array or an embedded document can have a name starting with the dollar sign ($). For the top-level fields, the name cannot start with a dollar ($) sign.
  3. Documents with duplicate field names are not supported. According to the MongoDB documentation, when a document with duplicate field names is inserted, no error will be thrown, but the document won't be inserted. Even the drivers will drop the documents silently. On the mongo shell, however, if such a document is inserted, it gets inserted correctly. However, the resulting document will have only the second field. That means the second occurrence of the field overwrites the value of the first.

    Note

    MongoDB (as of version 4.2.8) does not recommend field names starting with a dollar ($) sign or a dot (.). The MongoDB query language may not work correctly...

 

Summary

In this chapter, we have covered a detailed structure of MongoDB documents and document-based models, which is important before we dive into more advanced concepts in the upcoming chapters. We began our discussion with the transportation and storage of information in the form of JSON-like documents that provide a flexible and language-independent format. We studied an overview of JSON documents, the document structure, and basic data types, followed by BSON document specifications and differentiating between BSON and JSON on various parameters.

We then covered MongoDB documents, considering their flexibility, self-containment, relatability, and agility, as well as various data types provided by BSON. Finally, we made a note of MongoDB's limitations and restrictions for documents and learned why the limitations are imposed and why they are important.

In the next chapter, we will use the mongo shell and Mongo Compass to connect to an actual MongoDB server and manage...

About the Authors
  • Amit Phaltankar

    Amit Phaltankar is a software developer and a blogger experienced in building lightweight and efficient software components. He specializes in wiring web-based applications and handling large-scale data sets using traditional SQL, NoSQL, and big data technologies. He is experienced in many technology stacks and loves learning and adapting to newer technology trends. Amit is passionate about improving his skill set and loves guiding and grooming his peers and contributing to blogs. He is also an author of MongoDB Fundamentals.

    Browse publications by this author
  • Juned Ahsan

    Juned Ahsan is a software professional with more than 14 years of experience. He has built software products and services for companies and clients such as Cisco, Nuamedia, IBM, Nokia, Telstra, Optus, Pizzahut, AT&T, Hughes, Altran, and others. Juned has a vast experience in building software products and architecting platforms of different sizes from scratch. He loves to help and mentor others and is a top 1% contributor on StackOverflow. He is passionate about cognitive CX, cloud computing, artificial intelligence, and NoSQL databases.

    Browse publications by this author
  • Michael Harrison

    Michael Harrison started his career at the Australian telecommunications leader Telstra. He worked across their networks, big data, and automation teams. He is now a lead software developer and the founding member of Southbank Software, a Melbourne based startup that builds tools for the next generation of database technologies.

    Browse publications by this author
  • Liviu Nedov

    Liviu Nedov is a senior consultant with more than 20 years of experience in database technologies. He has provided professional and consulting services to customers in Australia and Europe. Throughout his career, he has designed and implemented large enterprise projects for customers like Wotif Group, Xstrata Copper/Glencore, and the University of Newcastle and Energy, Queensland. He is currently working at Data Intensity, which is the largest multi-cloud service provider for applications, databases, and business intelligence. In recent years, he is actively involved in MongoDB NoSQL database projects, database migrations, and cloud DBaaS (Database as a Service) projects.

    Browse publications by this author
MongoDB Fundamentals
Unlock this book and the full library FREE for 7 days
Start now