MongoDB is a database that stores data as documents, which look like JSON objects. This MongoDB tutorial teaches you to create a database, work with documents, search, update, delete, summarise and index data. All examples use one small set of students.
You do not need to know SQL first. It helps to understand objects and arrays. Commands here are for mongosh, the MongoDB shell.
MongoDB tutorial: how data is arranged
| Relational database | MongoDB | Example |
|---|---|---|
| Database | Database | school |
| Table | Collection | students |
| Row | Document | One student |
| Column | Field | name |
| Primary key | _id |
A unique value |
One document can hold text, numbers, dates, arrays and other documents:
{
name: "Anil",
city: "Hyderabad",
marks: 82,
skills: ["Java", "SQL"],
address: { area: "Madhapur", pin: "500081" }
}
MongoDB stores this in a format called BSON. BSON is like JSON but has more data types, such as dates and object IDs. MongoDB adds an _id if you do not give one.
Documents in a collection may have different fields. That does not mean every document should look different. Keep the shape consistent so your app can trust the data.
Interview note: "MongoDB has no schema" is too simple. It has a flexible schema, and you can add validation rules when a field must follow a fixed type.
Set it up or learn MongoDB online
You have two good choices:
- On your computer: install MongoDB Community Server and mongosh. Start the database service, then run
mongosh. - Online: make a Free cluster in MongoDB Atlas. Create a database user, allow your IP address, then copy the mongosh connection string.
As of December 2026, the MongoDB Atlas documentation lists a 0.5 GB data limit for a Free cluster. Check the official page because limits can change. It is enough for small exercises.
You can learn MongoDB online with Atlas, but do not paste its password into code you share. Also avoid leaving network access open to every address.
In mongosh, create and choose a database:
use school
MongoDB does not save an empty database yet. It creates the database when you add the first document. Now add your practice data:
db.students.insertMany([
{ name: "Anil", city: "Hyderabad", marks: 82,
skills: ["Java", "SQL"] },
{ name: "Meena", city: "Warangal", marks: 74,
skills: ["Python"] },
{ name: "Ravi", city: "Hyderabad", marks: 58,
skills: ["HTML", "CSS"] },
{ name: "Sara", city: "Vijayawada", marks: 91,
skills: ["Python", "SQL"] }
])
The reply contains acknowledged: true and four inserted IDs. Your IDs will be different from another student's IDs.
Learn MongoDB CRUD operations
CRUD means create, read, update and delete. To learn MongoDB CRUD operations, run each command and then use find to see what changed.
Create and read
insertOne adds one document. insertMany adds several. Find all students in Hyderabad:
db.students.find(
{ city: "Hyderabad" },
{ _id: 0, name: 1, marks: 1 }
)
The first object is the filter. The second chooses fields. 1 means show a field and 0 hides _id. With the starting data, the result has Anil with 82 and Ravi with 58.
These operators add conditions:
| Operator | Meaning | Example |
|---|---|---|
$gt / $gte |
Greater than / or equal | { marks: { $gte: 80 } } |
$lt / $lte |
Less than / or equal | { marks: { $lt: 60 } } |
$in |
One of many values | { city: { $in: ["Warangal"] } } |
$or |
At least one condition | { $or: [{ marks: 91 }, { city: "Warangal" }] } |
$exists |
Field is present or absent | { phone: { $exists: false } } |
Sort and limit a result:
db.students.find({}, { _id: 0, name: 1, marks: 1 })
.sort({ marks: -1 })
.limit(2)
-1 sorts from high to low. The first two students are Sara with 91 and Anil with 82. Use 1 to sort from low to high.
Update
db.students.updateOne(
{ name: "Ravi" },
{ $set: { marks: 65 } }
)
This changes one matching document. The reply has matchedCount: 1 and modifiedCount: 1 the first time. If you run it again, the match is still 1 but nothing needs to change, so modifiedCount is 0.
Other useful update operators are:
db.students.updateOne(
{ name: "Ravi" },
{ $inc: { marks: 5 }, $addToSet: { skills: "JavaScript" } }
)
$inc changes 65 to 70. $addToSet adds JavaScript only if it is not already in the array. Use updateMany to change every match.
Delete
db.students.deleteOne({ name: "Meena" })
The reply has deletedCount: 1. Three students remain. deleteMany removes every match.
Common mistake:
deleteMany({})deletes every document in a collection. Run the same filter withfindfirst. Check the results before changingfindto a delete command.
Query arrays and inner documents
Find a student with SQL in the skills array:
db.students.find(
{ skills: "SQL" },
{ _id: 0, name: 1 }
)
After the earlier changes, the names are Anil and Sara. MongoDB checks whether the array contains the value. Use $all when an array must contain every value:
db.students.find({ skills: { $all: ["Python", "SQL"] } })
Only Sara matches. For a field inside another document, use a quoted path:
db.students.updateOne(
{ name: "Anil" },
{ $set: { "address.area": "Madhapur" } }
)
db.students.find({ "address.area": "Madhapur" })
The update creates address and its area field. The search then returns Anil.
Summarise data with aggregation
An aggregation pipeline passes documents through steps. Each step changes or reduces the data.
db.students.aggregate([
{ $match: { marks: { $gte: 60 } } },
{
$group: {
_id: "$city",
average: { $avg: "$marks" },
students: { $sum: 1 }
}
},
{ $sort: { average: -1 } }
])
At this point Anil has 82, Ravi has 70 and Sara has 91. The output contains:
Vijayawada: average 91, students 1
Hyderabad: average 76, students 2
mongosh prints objects, not this short text. $match keeps useful documents, $group makes one result per city and $sort orders those results. Filter early so the next steps do less work.
| Stage | Similar SQL idea | Purpose |
|---|---|---|
$match |
WHERE | Keep some documents |
$group |
GROUP BY | Make totals |
$project |
SELECT columns | Choose or make fields |
$sort |
ORDER BY | Order results |
$lookup |
LEFT JOIN | Get related documents |
Indexes and good data design
An index helps MongoDB find data without checking every document. Create one on city and marks:
db.students.createIndex({ city: 1, marks: -1 })
The index can help a query that filters by city and sorts marks from high to low. See how a query runs:
db.students.find({ city: "Hyderabad" })
.sort({ marks: -1 })
.explain("executionStats")
Look for an index scan (IXSCAN) and compare totalDocsExamined with nReturned. A full collection scan is fine for four documents. It can become slow with a large collection.
Indexes use storage and add work to each write. Make them for real searches, not for every field.
For design, decide whether to embed or reference data:
- Embed an address if it belongs to one student and is usually read with that student.
- Reference a course by its ID if many students share it and it changes separately.
A document has a 16 MB size limit. Do not embed a list that can grow without limit, such as every login event.
Pro tip: Design from your app's common screens and queries. Ask what data you need together, how often it changes and whether a list can keep growing.
Connect MongoDB to a Node.js app
Install the official driver in a Node.js project with npm install mongodb. This small program reads one student:
import { MongoClient } from "mongodb";
const url = process.env.MONGODB_URL;
if (!url) throw new Error("MONGODB_URL is missing");
const client = new MongoClient(url);
try {
await client.connect();
const students = client.db("school").collection("students");
const student = await students.findOne({ name: "Anil" });
console.log(student?.marks ?? "Student not found");
} finally {
await client.close();
}
With the practice data, it prints 82. This is a one-time program, so it closes the client. A web server should create one client and reuse it for many requests. Follow the Node JS tutorial to build the server part.
Validate input before you place it in a query. If your app accepts a whole filter object from a user, that user may send operators you did not expect.
Learn MongoDB from scratch: practice plan
This MongoDB tutorial for beginners is easier to remember if you build a small library database:
- Add ten books with title, author, price, tags and copies.
- Find books below 500 rupees and sort them by price.
- Borrow a book by reducing copies, but only if copies are above zero.
- Find books with both of two tags.
- Count books and average price by author.
- Add an index for your main search and inspect it with
explain. - Connect the collection to a small API.
You can learn MongoDB from scratch with this one project. To learn MongoDB well, explain why you chose each field, filter and index. Our SQL vs NoSQL comparison can help you decide when documents are a good fit.
Finish with the MongoDB interview questions. Then use your API in the React task app, or see the full MERN stack path.
Frequently Asked Questions
Do I need SQL before MongoDB?
Is MongoDB free?
What is a document in MongoDB?
What is the difference between updateOne and updateMany?
Does MongoDB support relationships?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Check the Java Full Stack training details

