Introduction to MongoDB
When dealing with data, there are two types of data as we know – (i) structured data and (ii) unstructured data. Structured data is usually stored in a tabular form whereas unstructured data is not. To manage huge sets of unstructured data like log or IoT data, a NoSQL database is used.
MongoDB vs. SQL Databases Simplified
SQL Databases:
- Use tables with structured rows and columns.
- Data is queried using SQL.
- Designed for relational data storage.
MongoDB:
- Uses flexible documents (JSON-like).
- Data is stored in collections.
- Schema-less and suitable for non-relational data storage.
What is MongoDB ?
- MongoDB is an open-source NoSQL database written in C++ language. It uses JSON-like documents with optional schemas.
- It provides easy scalability and is a cross-platform, document-oriented database.
- MongoDB works on the concept of Collection and Document.
- It combines the ability to scale out with features such as secondary indexes, range queries, sorting, aggregations, and geospatial indexes.
- MongoDB is developed by MongoDB Inc. and licensed under the Server Side Public License (SSPL)
What are some of the advantages of MongoDB?
Some advantages of MongoDB are as follows:
- MongoDB supports field, range-based, string pattern matching type queries. for searching the data in the database
- MongoDB support primary and secondary index on any fields
- MongoDB basically uses JavaScript objects in place of procedures
- MongoDB uses a dynamic database schema
- MongoDB is very easy to scale up or down
- MongoDB has inbuilt support for data partitioning (Sharding)
When to use MongoDB?
You should use MongoDB when you are building internet and business applications that need to evolve quickly and scale elegantly. MongoDB is popular with developers of all kinds who are building scalable applications using agile methodologies.
MongoDB is a great choice if one needs to:
- Support a rapid iterative development.
- Scale to high levels of read and write traffic - MongoDB supports horizontal scaling through Sharding, distributing data across several machines, and facilitating high throughput operations with large sets of data.
- Scale your data repository to a massive size.
- Evolve the type of deployment as the business changes.
- Store, manage and search data with text, geospatial, or time-series dimensions.
What are the data types in MongoDB?
MongoDB supports a wide range of data types as values in documents. Documents in MongoDB are similar to objects in JavaScript. Along with JSON’s essential key/value–pair nature, MongoDB adds support for a number of additional data types. The common data types in MongoDB are:
- Null
- {"x" : null}
- Boolean
- {"x" : true}
- Number
- {"x" : 4}
- String
- {"x" : "foobar"}
- Date
- {"x" : new Date()}
- Regular expression
- {"x" : /foobar/i}
- Array
- {"x" : ["a", "b", "c"]}
- Embedded document
- {"x" : {"foo" : "bar"}}
- Object ID
- {"x" : ObjectId()}
- Binary Data
- Binary data is a string of arbitrary bytes.
- Code
- {"x" : function() { /* ... */ }}
How to perform queries in MongoDB?
The find method is used to perform queries in MongoDB. Querying returns a subset of documents in a collection, from no documents at all to the entire collection. Which documents get returned is determined by the first argument to find, which is a document specifying the query criteria.
Example:
> db.users.find({"age" : 24})
How do you Delete a Document?
The CRUD API in MongoDB provides deleteOne and deleteMany for this purpose. Both of these methods take a filter document as their first parameter. The filter specifies a set of criteria to match against in removing documents.
For example:
> db.books.deleteOne({"_id" : 3})
Updating a Document in MongoDB
Once a document is stored in the database, it can be updated using methods like updateOne, updateMany, and replaceOne:
- updateOne: Updates a single document that matches a given filter.
- updateMany: Updates multiple documents that match a given filter.
- replaceOne: Replaces an entire document that matches a given filter.
Example: Replacing a Document
Consider the following document in a MongoDB collection:
{
"_id": ObjectId("4b2b9f67a1f631733d917a7a"),
"name": "Alice",
"friends": 24,
"enemies": 2
}
To replace this document with a new one:
db.collection.replaceOne(
{ _id: ObjectId("4b2b9f67a1f631733d917a7a") }, // Filter
{ name: "Alice", friends: 30, enemies: 1 } // New document
);
This completely replaces the existing document. If you want to modify only specific fields instead of replacing the whole document, use updateOne with $set:
db.collection.updateOne(
{ _id: ObjectId("4b2b9f67a1f631733d917a7a") },
{ $set: { friends: 30, enemies: 1 } }
);
This updates only the friends and enemies fields while keeping the rest of the document unchanged.
How to add data in MongoDB?
The basic method for adding data to MongoDB is “inserts”. To insert a single document, use the collection’s insertOne method:
> db.books.insertOne({"title" : "Start With Why"})
For inserting multiple documents into a collection, we use insertMany. This method enables passing an array of documents to the database.
Key Features of MongoDB
MongoDB is a powerful NoSQL database known for its flexibility and scalability. Some of its key features include:
1. Indexing
MongoDB supports various types of indexing, improving query performance:
- Secondary Indexes – Additional indexes for faster lookups.
- Unique Indexes – Ensures uniqueness of values.
- Compound Indexes – Multiple fields combined in a single index.
- Geospatial Indexing – Enables location-based queries.
- Full-Text Indexing – Supports text search capabilities.
2. Aggregation Framework
MongoDB provides a powerful aggregation framework that processes data through a pipeline of operations, allowing complex data transformations and analytics.
3. Special Collection and Index Types
- TTL (Time-To-Live) Collections – Automatically deletes documents after a set period.
- Capped Collections – Fixed-size collections that maintain insertion order.
4. File Storage
MongoDB includes GridFS, a protocol for storing and retrieving large files (e.g., images, videos) along with metadata.
5. Sharding (Horizontal Scaling)
Sharding is MongoDB’s approach to distributing data across multiple servers, ensuring high availability and scalability. It is essential for handling large datasets efficiently.
How Does Scale-Out Work in MongoDB?
MongoDB’s document-oriented model makes it easier to scale out across multiple servers. Scaling is achieved using sharding, which distributes data across different machines.
Sharding Components:
- Mongos (Query Router) – Acts as an interface between client applications and the sharded cluster. It routes queries to the appropriate shards.
- Config Servers – Store metadata and configuration settings, managing distributed locks and cluster coordination. Each sharded cluster requires dedicated config servers.
- Shards – Store the actual data. MongoDB balances and redistributes documents across shards automatically.
With this architecture, MongoDB enables seamless horizontal scaling, handling growing datasets efficiently while maintaining performance.
What is the Mongo Shell?
Mongo Shell is a JavaScript-based command-line interface used to interact with a MongoDB instance. It allows users to perform administrative tasks, inspect databases, and explore data efficiently.
Starting the Mongo Shell
To launch the MongoDB shell, run the following commands:
$ mongod # Starts the MongoDB server $ mongo # Opens the Mongo Shell
Once connected, you’ll see an output similar to this:
MongoDB shell version: 4.2.0 connecting to: test >
JavaScript Support in Mongo Shell
Mongo Shell functions as a full-featured JavaScript interpreter, meaning you can execute JavaScript commands directly.
Example: Performing Basic Math
> x = 100; 100 > x / 5; 20
This flexibility makes Mongo Shell a powerful tool for database management, testing queries, and running scripts.
What are Databases in MongoDB?
MongoDB groups collections into databases. MongoDB can host several databases, each grouping together collections.
Some reserved database names are as follows:
admin
local
config
What is a Collection in MongoDB?
A collection in MongoDB is a group of documents. If a document is the MongoDB analog of a row in a relational database, then a collection can be thought of as the analog to a table.
Documents within a single collection can have any number of different “shapes.”, i.e. collections have dynamic schemas.
For example, both of the following documents could be stored in a single collection:
{"greeting" : "Hello world!", "views": 3}
{"signoff": "Good bye"}
What is a Document in MongoDB?
A Document in MongoDB is an ordered set of keys with associated values. It is represented by a map, hash, or dictionary. In JavaScript, documents are represented as objects:
{"greeting" : "Hello world!"}
Complex documents will contain multiple key/value pairs:
{"greeting" : "Hello world!", "views" : 3}
Understanding the $set Modifier in MongoDB
The $set operator in MongoDB is used to update or add fields in a document.
- If the specified field already exists,
$setupdates its value. - If the field does not exist,
$setcreates and assigns a value to it.
This is useful for modifying schemas, adding new fields, or updating user-defined keys.
Example: Using $set to Add a New Field
Existing Document in the users Collection:
{
"_id": ObjectId("4b253b067525f35f94b60a31"),
"name": "Alice",
"age": 23,
"sex": "female",
"location": "India"
}
Adding a New Field (favoriteBook) Using $set:
db.users.updateOne(
{ "_id": ObjectId("4b253b067525f35f94b60a31") },
{ "$set": { "favoriteBook": "Start with Why" } }
);
Updated Document After $set Operation:
{
"_id": ObjectId("4b253b067525f35f94b60a31"),
"name": "Alice",
"age": 23,
"sex": "female",
"location": "India",
"favoriteBook": "Start with Why"
}
This method is safe and efficient, ensuring that only the specified field is updated without affecting other data.
Geospatial Indexes in MongoDB
MongoDB provides two types of geospatial indexes for handling location-based queries:
1. 2dsphere Index
- Designed for spherical geometries, modeling the Earth as an oblate spheroid (slightly flattened at the poles).
- Based on the WGS84 datum, making it ideal for real-world geographic locations.
- Accurately calculates distances between locations, such as cities.
- Supports GeoJSON objects, including points, lines, and polygons.
Example: Storing a Point in GeoJSON Format
{
"name": "New York City",
"loc": {
"type": "Point",
"coordinates": [50, 2] // [longitude, latitude]
}
}
Example: Storing a Line (LineString) in GeoJSON Format
{
"name": "Hudson River",
"loc": {
"type": "LineString",
"coordinates": [[0,1], [0,2], [1,2]] // Array of points
}
}
2. 2d Index
- Used for flat, two-dimensional coordinate systems.
- Best suited for simple 2D plane calculations, not accounting for Earth's curvature.
- Mainly useful for small-scale applications, such as maps with local grid-based coordinates.
Choosing the Right Index
- Use 2dsphere for real-world geographic data where Earth's curvature matters.
- Use 2d for flat-plane coordinates when dealing with local, non-spherical maps.
Real-World Uses of Geospatial Indexes in MongoDB
Geospatial indexes in MongoDB are primarily used for location-based applications. They allow efficient querying of spatial data, such as finding nearby places, calculating distances, and mapping routes.
What is Indexing in MongoDB?
Indexing in MongoDB helps speed up queries by creating an ordered structure for specific fields. Instead of scanning the entire database, MongoDB looks at the index to quickly find the required data.
Think of an index in a book—instead of flipping through every page, you go straight to the topic and find the page number. Similarly, MongoDB uses indexes to improve search performance.
How to Create an Index?
To create an index, use the createIndex() method:
db.users.createIndex({ name: 1 });
Here, an index is created on the "name" field in ascending order (1).
Why Use Indexing?
✅ Faster Queries – Reduces search time.
✅ Efficient Sorting – Helps in sorting results quickly.
✅ Better Performance – Avoids full collection scans.:
> db.users.find({"username": "user101"}).explain("executionStats")
What are Transactions in MongoDB?
Transactions in MongoDB ensure multiple operations are executed as a single unit—either all succeed or all fail. This is useful when making changes to multiple documents, ensuring data consistency.
Why Use Transactions?
✅ Atomicity – All operations complete successfully or none at all.
✅ Consistency – Prevents partial updates.
✅ Reliability – Ideal for banking, orders, and inventory systems.
MongoDB Charts
MongoDB Charts is a built-in data visualization tool designed specifically for MongoDB databases. It provides an easy way to create interactive charts and dashboards without needing to write code in languages like Java or Python.
Key Features:
✅ Directly connect to MongoDB databases
✅ Create real-time, interactive visualizations
✅ Supports various chart types like bar charts, line charts, and geo-maps
✅ No need for complex ETL processes
Types of MongoDB Charts Implementations:
- MongoDB Charts PaaS (Platform as a Service) – A fully managed cloud service for visualizing MongoDB data.
- MongoDB Charts Server – A self-hosted version that allows organizations to deploy charts on their own infrastructure.
MongoDB Charts makes it easy to explore and present data insights directly from your database! 🚀
Pipeline in the MongoDB Aggregation Framework
In MongoDB, the aggregation pipeline is a powerful feature used to process and transform data within a collection. It works by passing documents through a sequence of stages, where each stage applies specific operations such as filtering, grouping, sorting, or transforming data.
How the Pipeline Works:
- Data flows through multiple stages, similar to a pipeline.
- Each stage processes the data and passes the output to the next stage.
- The final result is a transformed dataset based on the applied operations.
Common Aggregation Pipeline Stages:
- $match – Filters documents based on a condition (similar to
find). - $group – Groups documents by a specific field and applies aggregation functions like sum, average, etc.
- $project – Reshapes documents by including or excluding fields.
- $sort – Sorts documents based on a specified field.
- $limit – Restricts the number of documents in the output.
- $lookup – Performs a join with another collection.
Example Usage:
Suppose we have a sales collection and we want to calculate the total revenue per product.
db.sales.aggregate([
{ $group: { _id: "$product", totalRevenue: { $sum: "$price" } } },
{ $sort: { totalRevenue: -1 } }
])
💡 Output: A list of products with their total revenue, sorted in descending order.
The aggregation pipeline helps perform complex data manipulations efficiently within MongoDB! 🚀
i hope u have set ur mongodb with local data base
now in terminal show data base using command
show dbs
create database using command use "use" before database name
Create Collection using mongosh
There are 2 ways to create a collection.
Method 1
You can create a collection using the createCollection() database method.
Example
db.createCollection("posts")
Method 2
You can also create a collection during the insert process.
Example
We are here assuming object is a valid JavaScript object containing post data:
db.posts.insertOne(object)
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.
db.posts.insertOne({
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
tags: ["news", "events"],
date: Date()
})
insertMany()
To insert multiple documents at once, use the insertMany() method.
This method inserts an array of objects into the database.
db.posts.insertMany([
{
title: "Post Title 2",
body: "Body of post.",
category: "Event",
likes: 2,
tags: ["news", "events"],
date: Date()
},
{
title: "Post Title 3",
body: "Body of post.",
category: "Technology",
likes: 3,
tags: ["news", "events"],
date: Date()
},
{
title: "Post Title 4",
body: "Body of post.",
category: "Event",
likes: 4,
tags: ["news", "events"],
date: Date()
}
])
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.
db.posts.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.
Querying Data
To query, or filter, data we can include a query in our find() or findOne() methods.
db.posts.find( {category: "News"} )
the output will be data with news category from data base Posts
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.
Let's see what the "like" count for the post with the title of "Post Title 1":
first we need to find it
db.posts.find( { title: "Post Title 1" } )
Now let's update the "likes" on this post to 2. To do this, we need to use the $set operator.
Example
db.posts.updateOne( { title: "Post Title 1" }, { $set: { likes: 2 } } )
updateMany()
The updateMany() method will update all documents that match the provided query.
Example
Update likes on all documents by 1. For this we will use the $inc (increment) operator:
db.posts.updateMany({}, { $inc: { likes: 1 } })
Delete Documents
We can delete documents by 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.
Example
db.posts.deleteOne({ title: "Post Title 5" })
deleteMany()
The deleteMany() method will delete all documents that match the query provided.
Example
db.posts.deleteMany({ category: "Technology" })
MongoDB Query Operators
There are many query operators that can be used to compare and reference document fields.
Comparison
The following operators can be used in queries to compare values:
$eq: Values are equal$ne: Values are not equal$gt: Value is greater than another value$gte: Value is greater than or equal to another value$lt: Value is less than another value$lte: Value is less than or equal to another value$in: Value is matched within an array
Logical
The following operators can logically compare multiple queries.
$and: Returns documents where both queries match$or: Returns documents where either query matches$nor: Returns documents where both queries fail to match$not: Returns documents where the query does not match
Evaluation
The following operators assist in evaluating documents.
$regex: Allows the use of regular expressions when evaluating field values$text: Performs a text search$where: Uses a JavaScript expression to match documents
Aggregation Pipelines
Aggregation operations allow you to group, sort, perform calculations, analyze data, and much more.
Aggregation pipelines can have one or more "stages". The order of these stages are important. Each stage acts upon the results of the previous stage.
db.posts.aggregate([
// Stage 1: Only find documents that have more than 1 like
{
$match: { likes: { $gt: 1 } }
},
// Stage 2: Group documents by category and sum each categories likes
{
$group: { _id: "$category", totalLikes: { $sum: "$likes" } }
}
])
group
db.listingsAndReviews.aggregate(
[ { $group : { _id : "$property_type" } } ]
)
This will return the distinct values from the property_type field.
Aggregation $limit
This aggregation stage limits the number of documents passed to the next stage.
Example
db.movies.aggregate([ { $limit: 1 } ])
This will return the 1 data from the collection. or 1 movie details
Aggregation $sort
This aggregation stage groups sorts all documents in the specified sort order.
db.listingsAndReviews.aggregate([
{
$sort: { "accommodates": -1 }
},
{
$project: {
"name": 1,
"accommodates": 1
}
},
{
$limit: 5
}
])
This will return the documents sorted in descending order by the accommodates field.
The sort order can be chosen by using 1 or -1. 1 is ascending and -1 is descending.
Aggregation $match
This aggregation stage behaves like a find. It will filter documents that match the query provided.
Using $match early in the pipeline can improve performance since it limits the number of documents the next stages must process.
db.listingsAndReviews.aggregate([
{ $match : { property_type : "House" } },
{ $limit: 2 },
{ $project: {
"name": 1,
"bedrooms": 1,
"price": 1
}}
])
This will only return documents that have the property_type of "House".
Aggregation $count
This aggregation stage counts the total amount of documents passed from the previous stage.
db.restaurants.aggregate([
{
$match: { "cuisine": "Chinese" }
},
{
$count: "totalChinese"
}
])
This will return the number of documents at the $count stage as a field called "totalChinese".
Common Mongoose Question
What is Mongoose?
- Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution for modeling your application data and simplifies interactions with MongoDB databases.
What is a Schema in Mongoose?
- A schema in Mongoose defines the structure of documents within a collection, specifying the fields, their types, and any validation rules. It helps enforce data consistency and provides a blueprint for creating and querying documents.
How do you define a schema in Mongoose?
- To define a schema in Mongoose, you use the
mongoose.Schema()method and pass in an object specifying the fields and their types. For example:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
age: Number,
email: String
});
.How do you create a model in Mongoose?
- To create a model in Mongoose, you use the
mongoose.model()method and pass in a name for the model and the schema definition. For example:
const User = mongoose.model('User', userSchema);
How do you perform CRUD operations using Mongoose?
Mongoose provides methods for performing CRUD operations (Create, Read, Update, Delete) on MongoDB documents. For example:
Create: User.create()
Read: User.find(), User.findOne()
Update: User.updateOne(), User.findByIdAndUpdate()
Delete: User.deleteOne(), User.findByIdAndDelete()
What is middleware in Mongoose?
Middleware in Mongoose are functions that execute before or after certain operations, such as validation, saving, or removing documents. They allow you to perform custom logic, modify data, or execute additional tasks during these operations.
