MongoDB is a popular NoSQL database used to store and manage data in a flexible document format. It is commonly used in modern web applications, mobile applications, and backend systems.
MongoDB is an open-source, document-oriented database. Instead of storing data in traditional rows and columns, MongoDB stores data as documents inside collections.
For example, a student record can be stored as:
{
"_id": 1,
"name": "Rahul",
"age": 20,
"course": "ADCA",
"city": "Aurangabad"
}
In this example, the student's information is stored in a single document using field-value pairs.
NoSQL means "Not Only SQL." NoSQL databases provide different ways to store and manage data without requiring the traditional relational table structure.
Common types of NoSQL databases include:
MongoDB is a document database because it stores records as documents.
| SQL Database | MongoDB |
|---|---|
| Stores data in tables | Stores data in collections |
| Uses rows | Uses documents |
| Uses columns | Uses fields |
| Commonly uses a predefined schema | Supports flexible document structures |
| Example: MySQL | Example: MongoDB |
Both SQL and NoSQL databases can be useful. The right choice depends on the application's data structure, consistency requirements, queries, and scalability needs.
MongoDB uses three important concepts:
Example structure:
soopro_db
|
|-- students
|
|-- Document 1
|-- Document 2
|-- Document 3
Here, soopro_db is the database and
students is a collection containing student
documents.
Consider the following document for a student in a computer training institute:
{
"_id": 101,
"name": "Amit Kumar",
"age": 21,
"course": "Web Development",
"feesPaid": 5000,
"isActive": true
}
Explanation of the fields:
_id: Unique identifier for the document.name: Student's name.age: Student's age.course: Course selected by the student.feesPaid: Amount of fees paid.isActive: Boolean value indicating status.
MongoDB normally generates an ObjectId for
_id if you do not provide one when inserting
a document.
The following commands can be executed in MongoDB Shell
(mongosh).
Select or create a database:
use soopro_db
Insert a student document:
db.students.insertOne({
name: "Rahul",
age: 20,
course: "ADCA"
})
Display student documents:
db.students.find()
The insertOne() method inserts one document.
The find() method retrieves documents from
the collection.
Complete the following beginner assignments:
school_db.students collection.Q1. What type of database is MongoDB?
Q2. What contains documents in MongoDB?
Q3. Which method inserts one document?