Programs

MongoDB Tutorial for Beginners: Learn MongoDB in Simple Steps

MongoDB is a document database and a leading NoSQL database that is open-sourced. It is written in C++ and is a document-oriented NoSQL database used for high-volume data storage, content management and delivery, mobile and social infrastructures, user data management, etc.

It consists of a data model using which you can represent hierarchical relationships. It relies on JSON-like documents with optional schema and does not use rows and tables as used in traditional relational databases. The documents with key-value pairs are the fundamental units of data in MongoDB.

MongoDB stores data in JSON format. Its high demand is mainly based on its index on any attribute, replication and high availability, auto-sharding, rich queries, quick in-place updates, and rich community support. Let’s dive into mongodb query tutorial. 

MongoDB Features

The usability of this data-oriented database depends on certain integral features of Mongo DB:-

  • Each database consists of collections that further contain documents. These documents and their size and content can differ according to different numbers of fields. 
  • The document structure is based on how developers build classes and objects in their programs. 
  • The rows don’t require a predefined schema, as you can create the fields on the go.
  • With the MongoDB data model, you can represent hierarchical relationships for storing arrays and other complex structures.
  • MongoDB environments are very scalable. 
  • Application objects need not be converted or mapped to database objects.
  • Internal memory stores the windowed working set that enables easier access to data.
  • The structure of a single object is clear.
  • There aren’t any complex joins.
  • Its deep query-ability supports dynamic queries on documents.

Also, Check out our data science course to upskill yourself.

Things You Need To Know About MongoDB and RDBMS

MongoDB is a document-oriented, cross-platform database that delivers high performance, effective scalability, and high availability. It works based on Document and Collection. Every database in MongoDB has its distinct set of files, and ideally, a single MongoDB server has numerous databases. 

On the other hand, a Collection is a group of MongoDB documents equivalent to the RDBMS table. It exists inside a single database and does not enforce a schema. The Documents within a collection can have various fields, and all documents inside a collection are of related or similar purpose. A set of key-value pairs are called Documents having a dynamic schema, wherein the documents in the same collection need not have the same set of structure or fields. 

You will find the relationship of RDBMS terminology with MongoDB in the following table.

RDBMS MongoDB
Database Database
Tuple Document
Table Collection
Table join Embedded documents
column Field
Primary Key Primary Key (MongoDB offers the Default key _id)
Database Server and Client
mysqld/Oracle mongod
mysql/sqlplus mongo

Difference Between MongoDB and SQL databases

MongoDB is more flexible than SQL and offers better data availability. It is also portable and extendable. SQL databases are known for their durability and consistency. Thus, the best database solution depends on the kind of project one is involved in. 

MongoDB is better for development pipelines, while SQL databases are great for reliable organisational data transactions. MongoDB is great for processing and working with unstructured data. This NoSQL database is one of the best alternatives for feeding data pipelines and for applications, such as real-time analytics.

MongoDB is great for working with IoT devices and mobile/web applications. It is fast becoming the preferred choice for developers worldwide due to its flexibility and ability to scale up smoothly.

While SQL databases are great for working with structured data, Data Science and for advanced organizational tasks, MongoDB satisfies the requirements of modern developers and businesses through the effective development of software or online services.

Examples Of How To Use MongoDB 

Storing Nested Data Structures

The ability to nest objects within documents is one of the greatest features of MongoDB. To embed data inside documents, developers structure data in MongoDB rather than breaking it apart into various collections. 

Here is an example:-

{_id: ObjectId(“5effaa5662679b5af2c58829”),

 email: “email@example.com”,

 name: {given: “Lily”, family: “Mona”},

 age: 31,

 addresses: [{label: “home”,

           street: “22 1b Baker Street”,

           city: “London”,

           state: “ENG”,

           zip: “NW1 6XE”,

           country: “UK”},

          {label: “mom”,

           street: “555 Park Street”,

           city: “Lake Town”,

           province: “Ontario”,

           country: “CA”}]

           }

The name field is the nested object having given and family name components in the addresses field where multiple addresses are stored in one array. Each address can have various fields making it easy to store other data types.

Using the MongoDB Shell

The MongoDB shell is mainly used for navigating, manipulating and inspecting document data. When MongoDB is run on a local machine, firing up the shell connects to MongoDB at localhost on the standard port. Make sure to add the connection string after command mongo if you need to connect to a MongoDB Atlas cluster or other remote instance.

You will find quick shell examples below:-

List Collections

> use my_database;

> show collections;

users

posts

>

List Databases

> show dbs;

admin 0.000GB

config   0.000GB

local 0.000GB

my_database  0.004GB

>

Explore our Popular Data Science Courses

Find the First Document in a Collection

> db.users.findOne()

{

“_id”: ObjectId(“5ce45d7606444f199acfba1e”),

“name”: {given: “Anna”, family: “Smith”},

“email”: “email@example.com”

“age”: 36

}

>

Count Documents in a Collection

> use my_database;

> db.users.count()

20234

>

Find a Document by ID

> db.users.findOne({_id: ObjectId(“5ce45d7606444f199acfba1e”)})

{

“_id”: ObjectId(“5ce45d7606444f199acfba1e”),

“name”: {given: “Anna”, family: “Smith”},

“email”: “email@example.com”,

“age”: 36

}

>

Querying MongoDB Collections

The same syntax in the MongoDB Query Language (MQL) is used in the documents that can be used in advanced querying. You will find the MongoDB query examples below:

Find a Limited Number of Results

> db.users.find().limit(10)

>

Find Users by Family name

> db.users.find({“name.family”: “Smith”}).count()

1

Note that we enclose “name.family” in quotes, because it has a dot in the middle.

Query Documents by Numeric Ranges

// All posts having “likes” field with numeric value greater than one:

> db.post.find({likes: {$gt: 1}})

// All posts having 0 likes

> db.post.find({likes: 0})

// All posts that do NOT have exactly 1 like

> db.post.find({likes: {$ne: 1}})

Sort Results by a Field

// order by age, in ascending order (smallest values first)

> db.user.find().sort({age: 1})

{

    “_id”: ObjectId(“5ce45d7606444f199acfba1e”),

    “name”: {given: “Alex”, family: “Smith”},

    “email”: “email@example.com”,

    “age”: 27

}

{

    _id: ObjectId(“5effaa5662679b5af2c58829”),

    email: “email@example.com”,

    name: {given: “Jesse”, family: “Xiao”},

    age: 31

}

>

// order by age, in descending order (largest values first)

> db.user.find().sort({age: -1})

{

    _id: ObjectId(“5effaa5662679b5af2c58829”),

    email: “email@example.com”,

    name: {given: “Lilly”, family: “Mona”},

    age: 31

}

{

    “_id”: ObjectId(“5ce45d7606444f199acfba1e”),

    “name”: {given: “Anna”, family: “Smith”},

    “email”: “email@example.com”,

    “age”: 36

}

>

Top Data Science Skills to Learn in 2022

Conclusion

MongoDB’s scalability makes it one of the most extensively used databases because it provides a number of benefits in the field of software development and data science. Pursuing a career in these fields is a lucrative option. upGrad’s Executive PG Programme in Data Science is a great place to kickstart your career in data science and other related fields. 

Why is MongoDB so easy to scale?

MongoDB is easy to scale because it is not an SQL database, as the data inside MongoDB is not coupled relationally. Data in MongoDB is stored in a self-contained format which enables easy horizontal scaling by distributing these documents across multiple systems (nodes).

What is the difference between MongoDB and database systems such as MariaDB and MySQL?

MongoDB is a NoSQL database while MariaDB and MySQL are SQL databases. Also, MongoDB is a Non-relational database while the other two are relational databases.

Why is MongoDB so popular?

MongoDB is an essential part of the MERN stack in web development. It is also easy to deploy and scale projects on MongoDB. MongoDB is known for its scalability. It is a great fit for any development pipeline.

Want to share this article?

Be Certified Data Engineer

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks