UNIT V INTRODUCTION TO MONGODB (9 Hrs)
Introduction to MongoDB: definition of MongoDB: document database - An
overview of MongoDB architecture. Introduction to mongo dB basics - core
concepts and vocabulary - mongo dB databases - mongo dB collections -
mongo dB documents, introduction to mongo dB shell, types of storage
engines.
MongoDB is a popular NoSQL database that offers a flexible, scalable,
and high-performance way to store data. In
MongoDB, Databases, Collections, and Documents are the fundamental
building blocks for data storage and management. Understanding these
components is crucial for efficiently working with MongoDB.
In this article, we will explain the core components of
MongoDB: Databases, Collections, and Documents, which are fundamental
to understanding how MongoDB stores and organizes data. We’ll dive into the
structure and significance of each component, providing practical examples.
What is a Database in MongoDB?
A Database in MongoDB is a container for data that holds multiple
collections. MongoDB allows the creation of multiple databases on a single
server, enabling efficient data organization and management for various
applications. It’s the highest level of structure within the MongoDB system.
1. Multiple Databases: MongoDB allows you to create multiple databases on
a single server. Each database is logically isolated from others.
2. Default Databases: When you start MongoDB, three default databases are
created: admin, config, and local. These are used for internal purposes.
3. Database Creation: Databases are created when you insert data into
them. You can create or switch to a database using the following command:
use <database_name>
This command actually switches you to the new database if the given name
does not exist and if the given name exists, then it will switch you to
the existing database. Now at this stage, if you use the show command to
see the database list where you will find that your new database is not
present in that database list because, in MongoDB, the database is actually
created when we start entering data in that database.
4. View Database: To see how many databases are present in your MongoDB
server, write the following statement in the mongo shell:
show dbs
Here, we freshly started MongoDB so we do not have a database except these
three default databases, i.e, admin, config, and local.
Here, we create a new database named GeeksforGeeks using the use
command. After creating a database when we check the database list we do
not find our database on that list because we do not enter any data in
the GeeksforGeeks database.
Naming Restriction for Database:
Before creating a database we should first learn about the naming
restrictions for databases:
Database names must be case-insensitive.
The names cannot contain special characters such as /, ., $, *, |, etc.
MongoDB database names cannot contain null characters(in windows, Unix,
and Linux systems).
MongoDB database names cannot be empty and must contain less than 64
characters.
For windows user, MongoDB database names cannot contain any of these
following characters:
/\. "$*:|?
For Unix and Linux users, MongoDB database names cannot contain any of
these following characters:
/\. "$
Example:
use LibraryDB # Switch to the LibraryDB database
What is a Collection in MongoDB?
A Collection in MongoDB is similar to a table in relational databases. It holds
a group of documents and is a part of a database. Collections provide structure
to data, but like the rest of MongoDB, they are schema-less.
Schemaless
As we know that MongoDB databases are schemaless. So, it is not necessary
in a collection that the schema of one document is similar to another
document. Or in other words, a single collection contains different types of
documents like as shown in the below example
where mystudentData collection contain two different types of documents:
Multiple Collections per Database
A single database can contain multiple collections, each storing different types
of documents.
Naming Restrictions for Collection:
Before creating a collection we should first learn about the naming restrictions
for collections:
Collection name must starts with an underscore (`_`) or a letter (a-z or A-
Z)
Collection name should not start with a number, and does not contain $,
empty string, null character and does not begin with prefix `system.` as this
is reserved for MongoDB system collections.
The maximum length of the collection name is 120 bytes(including the
database name, dot separator, and the collection name).
Example:
[Link]({ title: "Learn MongoDB", author: "Jane Doe", year: 2023 })
Creating collection
After creating database now we create a collection to store documents. The
collection is created using the following syntax:
db.collection_name.insertOne({..})
Here, insertOne() function is used to store single data in the specified
collection. And in the curly braces {} we store our data or in other words, it
is a document.
For Example:
In this example, we create a collection named as the Author and we insert
data in it with the help of insertOne() function. Or in other words, {name:
“Ankita”} is a document in the Author collection, and in this document,
the name is the key or field and “Ankita” is the value of this key or field.
After pressing enter we got a message(as shown in the above image) and
this message tells us that the data enters successfully (i.e., “acknowledge”:
true) and also assigns us an automatically created id.
It is the special feature provided by MongoDB that every document
provided a unique id and generally, this id is created automatically, but
you are allowed to create your own id (must be unique).
What is a Document in MongoDB?
In MongoDB, the data records are stored as BSON documents. Here, BSON
stands for binary representation of JSON documents, although BSON contains
more data types as compared to JSON. The document is created using field-
value pairs or key-value pairs and the value of the field can be of any BSON
type.
Syntax:
{
field1: value1
field2: value2
….
fieldN: valueN
}
Document Structure:
A document in MongoDB is a flexible data structure made up of field-value
pairs. For instance:
{
title: "MongoDB Basics",
author: "John Doe",
year: 2025
}
Naming restriction for Document Fields:
Before moving further first you should learn about the naming restrictions for
fields:
Fields in documents must be named with strings
The _id field name is reserved to use as a primary key. And the value of this
field must be unique, immutable, and can be of any type other than an
array.
The field name cannot contain null characters.
The top-level field names should not start with a dollar sign ($).
Document Size:
The maximum size of the BSON document is 16MB. It ensures that the single
document does not use too much amount of RAM or bandwidth(during
transmission). If a document contains more data than the specified size, then
MongoDB provides a GridFS API to store such type of documents. A single
document may contain duplicate fields.
MongoDB always saves the order of the fields in the documents except for the
_id field (which always comes in the first place) and the renaming of fields may
change the order of the fields in the documents.
What is the _id Field in MongoDB?
In MongoDB, every document store in the collection must contain a unique
_id field it is just like a primary key in a relational database. The value of the
_id field can be set by the user or by the system (if the user does not create an
_id field, then the system will automatically generate an ObjectId for _id field).
Automatic ObjectId Generation: When you don’t define the _id field,
MongoDB generates a unique ObjectId by default.
Custom _id: You can set the _id field to a custom value, provided it is
unique within the collection.
Example with ObjectId:
Here, name, branch, course, and paid field contain values of string type.
amount field contains the value of integer type and _id field is generated by
the system.
Example with Custom _id:
Here, the _id field is created by the user. When you paste data in the functions
always use close parenthesis after pasting the data into the function. If you
use close parenthesis before pasting data in the function, then you will get an
error.
Key Differences Between Databases, Collections, and Documents
Database: A container for collections, providing structure and logical
isolation for data.
Collection: A group of documents within a database, similar to a table in
relational databases.
Document: A single data record within a collection, stored as a BSON
object.
Practical Example: Creating a Database, Collection, and Document
Here’s how you can create a database, collection, and document in MongoDB
step by step:
1. Create or Switch to a Database
use LibraryDB
2. Create a Collection and Insert a Document
[Link]({
title: "MongoDB for Beginners",
author: "Alice Johnson",
year: 2023
})
3. Verify the Insertion
[Link]()
This will display the document stored in the books collection within
the LibraryDB database.
MongoDB Indexes and the _id Field
Automatic Index on _id: MongoDB automatically creates a unique index on
the _id field for every collection. This index helps MongoDB quickly find
documents based on their unique identifier.
Best Practices for MongoDB Databases, Collections, and Documents
Descriptive Names: Name databases and collections based on their
content for better organization. For example,
use user_data or transaction_records for database and collection names.
Avoid Special Characters: Ensure that database and collection names do
not contain special characters like $ or spaces.
Design Efficient Documents: While MongoDB is schema-less, it’s
important to design documents that make sense for your application’s data
structure. Use nested documents and arrays when appropriate to model
complex data.
How to Create a MongoDB Database Using Mongo Shell
To create a new MongoDB database using Mongo Shell use the “use
Database_Name” command. This command creates a new database if it
doesn’t exist, otherwise, it will return the existing database.
The newly created database will not be present in the list of databases. To
display the database in the database list, insert at least one document into it.
Syntax:
use Database_Name
Create a New Database Using Mongo Shell Example
The below image shows new database creation using Mongo Shell:
In MongoDB default database is test. If you did not create any Database and
started inserting collection then all collections are stored in the Default
Database.
How to View the List of Databases in MongoDB
To view a list of all existing MongoDB databases, use the following command:
show dbs
This will return a list of all databases currently stored in MongoDB. Note that if
your new database doesn’t contain any collections, it won’t appear in this list
until you add a document to it.
Show List of Databases Example
The below example shows how to see list of databases using Mongo Shell.
Check Current Database
To check the current database you’re working with, simply use the following
command:
db
This will return the name of the database that’s currently active. If you’ve just
created a new database, it will return the name of the newly selected
database.
Check Current Database Example
The below image shows how to check current database using Mongo Shell.
Switch to Other Database
To switch to a different database, use the use command again followed by the
name of the desired database. If the database does not exist, MongoDB will
create it:
use AnotherDB
Switch to other Database Example
The below image shows how to switch to another database using Mongo Shell.
In the above Example, First we check current Database name using db
command which was UserDB then we use “use test” command to switch to
database test.
Insert the First Document to Make the Database Visible
Once you’ve created your database, you can insert a document into a
collection to make the database visible in the database list. Here’s an example
of inserting a document into a new collection:
[Link]({ name: "John Doe", age: 30 })
Once we insert a document, the TestDB database will appear in the list of
databases when we run the show dbs command.
CRUD operations Create, Read, Update, and Delete—are essential for
interacting with databases. In MongoDB, CRUD operations allow users to
perform various actions like inserting new documents, reading data, updating
records, and deleting documents from collections. Mastering these operations
is fundamental to working with MongoDB and building efficient applications.
In this article, we will explain each of the four core CRUD operations in
MongoDB, their use cases, and provide examples to help you perform these
operations effectively.
What are CRUD Operations in MongoDB?
Now that we know the components of the CRUD operation, let’s learn about
each individual operation in MongoDB. We will know what each operation does,
and the methods to perform these operations in MongoDB. We will create,
read, update and delete documents from MongoDB server.
Create: Add new documents to a collection.
Read: Retrieve documents from a collection.
Update: Modify existing documents.
Delete: Remove documents from a collection.
These operations form the core functionality of interacting with MongoDB
databases and are essential for managing data.
1. Create Operations
The create or insert operations are used to insert or add new documents in the
collection. If a collection does not exist, then it will create a new collection in
the database. We can perform, create operations using the following methods
provided by the MongoDB:
Method Description
[Link]( It is used to insert a single document in the
) collection.
[Link] It is used to insert multiple documents in the
y() collection.
[Link]() It is used to create an empty collection.
Create Operations Example
Let’s look at some examples of the Create operation from CRUD in MongoDB.
Example 1:
In this example, we are inserting details of a single student in the form of
document in the student collection using [Link]() method.
2. Read Operations
The Read operations are used to retrieve documents from the collection, or in
other words, read operations are used to query a collection for a document. We
can perform read operation using the following method provided by the
MongoDB:
Method Description
[Link]() It is used to retrieve documents from the collection.
[Link] Retrieves a single document that matches the query
e() criteria.
Note: pretty() method is used to decorate the result such that it is easy to
read.
Read Operations Example
In this example, we are retrieving the details of students from the student
collection using [Link]() method.
3. Update Operations
The update operations are used to update or modify the existing document in
the collection. We can update a single document or multiple documents that
match a given query. We can perform update operations using the following
methods provided by the MongoDB:
Method Description
[Link] It is used to update a single document in the
() collection that satisfy the given criteria.
[Link] It is used to update multiple documents in the
ny() collection that satisfy the given criteria.
[Link] It is used to replace single document in the
e() collection that satisfy the given criteria.
Update Operations Example
Let’s look at some examples of the update operation from CRUD in MongoDB.
Example 1:
In this example, we are updating the age of Sumit in the student collection
using [Link]() method.
4. Delete Operations
The delete operation are used to delete or remove the documents from a
collection. We can delete documents based on specific criteria or remove all
documents. We can perform delete operations using the following methods
provided by the MongoDB:
Method Description
[Link] It is used to delete a single document from the
e() collection that satisfy the given criteria.
[Link] It is used to delete multiple documents from the
ny() collection that satisfy the given criteria.
Delete Operations Examples
Let’s look at some examples of delete operation from CRUD in MongoDB.
Example 1:In this example, we are deleting a document from the student
collection using [Link]() method.