BASICS OF
MONGODB
Introduction
The MongoDB is an open-source document database and leading NoSQL database.
It stores data in a type of JSON format called BSON.
MongoDB features are flexible data models that allows the storage of unstructured data. This
provides full support indexing, replication, capabilities and also user friendly APIs.
The MongoDB is a multipurpose dataset that is used for modern application development and cloud
environments. This scalable architecture enables us to handle system demands and also adding
more nodes to distribute the load.
Records in a MongoDB database are called documents, and the field values may include numbers,
strings, booleans, arrays, or even nested documents.
MongoDB Applications
MongoDB is a NoSQL database. MongoDB provides following functionality to the database
programmers −
• Stores user data, comments and metadata
• MongoDB performs complex analytics queries and stores the behavioral data.
• This is used to manage chain data and optimize logistics.
• Environmental data and IoT devices are stored and analyzed.
Basic Commands
List of standard MongoDb commands to interact with the database, These commands are CREATE,
READ, INSERT, UPDATE, DELETE, DROP and AGGREGATE can be classified into following groups based
on their nature −
CREATE Creates a new table in the database and other objects in the database.
INSERT Inserts collection name in existing database.
DROP Deletes an entire table or specified objects in the database.
UPDATE Updates the document into a collection.
MongoDB works on concept of collection and document. MongoDB is a document database which
is often referred to as a non-relational database. This does not mean that relational data cannot be
stored in document databases. It means that relational data is stored differently. A better way to
refer to it is as a non-tabular database.
MongoDB stores data in flexible documents. Instead of having multiple tables you can simply keep all
of your related data together. This makes reading your data very fast.
Database
Database is a physical container for collections. Each database gets its own set of files on the file
system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database.
Collections do not enforce a schema. Documents within a collection can have different fields.
Typically, all documents in a collection are of similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema.
Dynamic schema means that documents in the same collection do not need to have the
same set of fields or structure, and common fields in a collection's documents may hold
different types of data.
Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.
Advantages of MongoDB over RDBMS
• Schema less − MongoDB is a document database in which one collection holds different
documents. Number of fields, content and size of the document can differ from one
document to another.
• Structure of a single object is clear.
• No complex joins.
• Deep query-ability. MongoDB supports dynamic queries on documents using a document-
based query language that's nearly as powerful as SQL.
• Tuning.
• Ease of scale-out − MongoDB is easy to scale.
• Conversion/mapping of application objects to database objects not needed.
• Uses internal memory for storing the (windowed) working set, enabling faster access of data.
Example
Following example shows the document structure of a blog site, which is simply a comma separated key value pair.
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: ‘xxx',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can provide _id while inserting the document. If you don’t
provide then MongoDB provides a unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id, next 2
bytes for process id of MongoDB server and remaining 3 bytes are simple incremental VALUE.
Basic Commands
Show all databases
To see all available databases, in your terminal type show dbs.
Change or Create a Database
change or create a new database by typing use then the name of
the database.
db.dropDatabase() command is used to drop a existing database.
Create Collection using mongosh
There are 2 ways to create a collection.
Method 1
You can create a collection using the createCollection() database
method.
Syntax: db.createCollection(“collectionname")
Method 2
Can also create a collection during the insert process. This will create
collection if it does not already exist.
Syntax: db.collectionname.insertOne(object)
The drop() Method
MongoDB's db.collection.drop() is used to drop a collection from the
database.
Syntax: db.COLLECTION_NAME.drop()
Basic Commands
Insert Documents
There are 2 methods to insert documents into a
MongoDB database.
insertOne()
To insert a single document, use the insertOne()
method.
This method inserts a single object into the database. If
you try to insert documents into a collection that does
not exist, MongoDB will create the collection
automatically.
insertMany()
To insert multiple documents at once, use the
insertMany() method.
This method inserts an array of objects into the
database.
Basic Commands
Find Data
There are 2 methods to find and select data from a
MongoDB collection, find() and findOne().
find()
To select data from a collection in MongoDB, we can
use the find() method.
This method accepts a query object. If left empty, all
documents will be returned.
Syntax: db.collectionname.find()
findOne()
To select only one document, we can use the
findOne() method.
This method accepts a query object. If left empty, it
will return the first document it finds.
Note: This method only returns the first match it finds.
Basic Commands
Querying Data
To query, or filter, data we can include a query in our
find() or findOne() methods.
Example: db.student.find({dept: ‘IT’})
Projection
Both find methods accept a second parameter
called projection.
This parameter is an object that describes which fields
to include in the results.
Note: This parameter is optional. If omitted, all fields
will be included in the results.
Example: db.student.find({}, {name: 1, dept: 1})
db.student.find({}, {_id: 0, dept: 0})
Basic Commands
Update Document
To update an existing document we can use the
updateOne() or updateMany() methods.
The first parameter is a query object to define which
document or documents should be updated.
The second parameter is an object defining the
updated data.
updateOne()
The updateOne() method will update the first
document that is found matching the provided
query
Example:db.student.updateOne({name:'Jane
Doe'},{$set:{age:20}})
Basic Commands
Update Document
To update an existing document we can use the
updateOne() or updateMany() methods.
The first parameter is a query object to define which
document or documents should be updated.
The second parameter is an object defining the
updated data.
updateOne()
The updateOne() method will update the first
document that is found matching the provided
query
Example:db.student.updateOne({name:'Jane
Doe'},{$set:{age:20}})
Insert if not found
If you would like to insert the document if it is not
found, you can use the upsert option.
Basic Commands
Update Operators
There are many update operators that can be used during document updates.
The following operators can be used to update fields:
$currentDate: Sets the field value to the current date
$inc: Increments the field value
$rename: Renames the field
$set: Sets the value of a field
$unset: Removes the field from the document
The following operators assist with updating arrays.
$addToSet: Adds distinct elements to an array
$pop: Removes the first or last element of an array
$pull: Removes all elements from an array that match the query
$push: Adds an element to an array
Basic Commands
updateMany()
The updateMany() method will update all documents that match
the provided query.
Update age on all documents by 1. For this use the $inc (increment)
operator
Example: db.student.updateMany({},{$inc: {age:1}})
Basic Commands
Delete Documents
delete documents can be done using the methods
deleteOne() or deleteMany().
These methods accept a query object. The
matching documents will be deleted.
deleteOne()
The deleteOne() method will delete the first
document that matches the query provided.
Eg. db.student.deleteOne({name:'Aaron'})
deleteMany()
The deleteMany() method will delete all documents
that match the query provided.
Eg.db.student.deleteMany({age:21})
Basic Commands Logical
The following operators can logically compare
MongoDB Query Operators
multiple queries.
There are many query operators that can be
$and: Returns documents where both queries
used to compare and reference document
match
fields.
$or: Returns documents where either query
Comparison
matches
The following operators can be used in queries to
$nor: Returns documents where both queries fail
compare values:
to match
$eq: Values are equal
$not: Returns documents where the query does
$ne: Values are not equal
not match
$gt: Value is greater than another value
Evaluation : The following operators assist in
$gte: Value is greater than or equal to another
evaluating documents.
value
$regex: Allows the use of regular expressions
$lt: Value is less than another value
when evaluating field values
$lte: Value is less than or equal to another value
$text: Performs a text search
$in: Value is matched within an array
$where: Uses a JavaScript expression to match
documents
Basic Commands
The Limit() Method
To limit the records in MongoDB, you need to use limit()
method. The method accepts one number type
argument, which is the number of documents that you
want to be displayed.
Syntax
db.COLLECTION_NAME.find().limit(NUMBER)
If we don't specify the number argument in limit()
method then it will display all documents from the
collection.
Skip() Method
There is one more method skip() which also accepts
number type argument and is used to skip the number
of documents.
Syntax
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMB
ER)
The default value in skip() method is 0.
Basic Commands
sort() Method
To sort documents in MongoDB, you need to use sort()
method. The method accepts a document containing
a list of fields along with their sorting order. To specify
sorting order 1 and -1 are used. 1 is used for ascending
order while -1 is used for descending order.
Syntax: db.COLLECTION_NAME.find().sort({KEY:1})
Basic Commands
The aggregate() Method
Aggregations operations process data records and
return computed results. Aggregation operations group
values from multiple documents together, and can
perform a variety of operations on the grouped data to
return a single result. In SQL count(*) and with group by
is an equivalent of MongoDB aggregation.
syntax of aggregate() method is as follows −
db.COLLECTION_NAME.aggregate(AGGREGATE_OPER
ATION)
$sumSums up the defined value from all documents in
the collection.
$avgCalculates the average of all given values from
all documents in the collection.
$min,$maxGets the minimum/maximum of the
corresponding values from all documents in the $pushInserts the value to an array in the
resulting document.
collection. $addToSetInserts the value to an array in the
$first,$lastGets the first/last document from the source resulting document but does not create
documents according to the grouping. duplicates.
Connecting to MongoDB
To use MongoDB into your Python application by
initiating a connection to the database.
# Importing the 'pymongo' module for MongoDB
interaction
import pymongo
# Try to create a MongoDB client and connect to the
server
try:
# Creating a MongoClient to connect to the local
MongoDB server
client =
pymongo.MongoClient("mongodb://localhost:27017/")
# Selecting a specific database
database = client["your_database_name"]
# Printing a message indicating a successful
connection
print("Connected to MongoDB")
except Exception as e:
# Handling exceptions and printing an error
message if connection fails
print(f"Error: {e}")
# Method to insert student data into the 'students' collection
def insert(self, student):
try:
# Creating a dictionary with student details
data = {
'_id': student.sid,
'username': student.username,
'email': student.email,
'year': student.year,
'department': student.department
}
# Inserting the student data into the 'students' collection and obtaining the
inserted ID
sid = self.collection.insert_one(data).inserted_id
# Printing a message indicating the successful insertion of data with the
obtained ID
print(f"Data inserted with ID: {sid}")
except Exception as e:
# Handling exceptions and printing an error message if data insertion fails
print(f"Error: {e}")
# Method to fetch all students' data from the 'students' collection
def fetch_all(self):
# Querying the 'students' collection to find all data
data = self.collection.find()
return data
# Method to update a specific student's data based on student ID
def update(self, sid, student):
# Creating a dictionary with updated student details
data = {
'username': student.username,
'email': student.email,
'year': student.year,
'department': student.department
}
# Updating the student data in the 'students' collection
self.collection.update_one({'_id': sid}, {"$set": data})
# Method to delete a specific student's data based on student ID
def delete(self, sid):
# Deleting a student's data from the 'students' collection based on
student ID
self.collection.delete_one({'_id': sid})
Viewing Data in MongoDB Compass Dashboard