Lesson 9 of 50 – Basic MongoDB Commands
18%

Basic MongoDB Commands

MongoDB provides several commands to create databases, manage collections, insert documents, retrieve records, update data, and delete documents. In this lesson, we will learn the most commonly used MongoDB commands with practical examples.

1. Display All Databases

The show dbs command displays the databases that contain stored data.

show dbs

Example output:

admin       40.00 KiB
config      72.00 KiB
local       80.00 KiB
school      40.00 KiB

Note: A database may not appear in show dbs until data has been stored in it.

2. Select or Create a Database

Use the use command to switch to a database. If the database does not exist, MongoDB selects it and creates it when data is first stored.

use school

Output:

switched to db school

Check the current database:

db

3. Create a Collection

A collection stores documents. Use createCollection() to create one explicitly.

db.createCollection("students")

List the collections in the current database:

show collections

4. Insert Documents

The insertOne() method inserts one document into a collection.

db.students.insertOne({
    name: "Rahul",
    age: 20,
    course: "ADCA"
})

To insert multiple documents, use insertMany().

db.students.insertMany([
    {
        name: "Amit",
        age: 21,
        course: "Tally Prime"
    },
    {
        name: "Priya",
        age: 19,
        course: "Web Development"
    },
    {
        name: "Neha",
        age: 22,
        course: "Python"
    }
])

5. Find Documents

The find() method retrieves documents from a collection.

Display all students:

db.students.find()

Display students in a readable format:

db.students.find().pretty()

Find students whose course is ADCA:

db.students.find({
    course: "ADCA"
})

Find one matching document:

db.students.findOne({
    name: "Rahul"
})

6. Update Documents

Use updateOne() to update the first document matching a condition.

db.students.updateOne(
    { name: "Rahul" },
    { $set: { age: 21 } }
)

The $set operator changes the specified field without replacing the entire document.

Use updateMany() to update every matching document.

db.students.updateMany(
    { course: "ADCA" },
    { $set: { status: "Active" } }
)

7. Delete Documents

The deleteOne() method deletes the first matching document.

db.students.deleteOne({
    name: "Rahul"
})

The deleteMany() method deletes all documents matching the given condition.

db.students.deleteMany({
    status: "Inactive"
})

Warning: Always check your filter before running a delete command. An incorrect filter can remove more documents than intended.

8. Count Documents

Use countDocuments() to count documents matching a condition.

Count all student documents:

db.students.countDocuments({})

Count students enrolled in ADCA:

db.students.countDocuments({
    course: "ADCA"
})

9. Sort and Limit Results

Use sort() to arrange documents and limit() to restrict the number of results.

Sort students by age in ascending order:

db.students.find().sort({
    age: 1
})

Sort students by age in descending order:

db.students.find().sort({
    age: -1
})

Display only the first two documents:

db.students.find().limit(2)

10. Drop a Collection or Database

The drop() method removes a collection.

db.students.drop()

To remove the current database, use:

db.dropDatabase()

Important: These commands permanently remove database objects or data. Use them only in a practice database when you are learning.

11. Quick Reference Table

Command Purpose
show dbs Display databases
use school Select a database
show collections List collections
db.createCollection() Create a collection
insertOne() Insert one document
find() Retrieve documents
updateOne() Update one matching document
deleteOne() Delete one matching document
countDocuments() Count matching documents
drop() Remove a collection
db.dropDatabase() Remove the current database

📝 Practical Assignment

Complete these tasks in MongoDB Shell (mongosh):

  1. Create or select a database named school.
  2. Create a collection named students.
  3. Insert five student documents with name, age, and course.
  4. Display all student documents.
  5. Find students who are enrolled in Python.
  6. Update one student's age.
  7. Count all student documents.
  8. Display students in descending order of age.

🧠 Quick Quiz

1. Which command displays databases?


2. Which method inserts one document?


3. Which method counts matching documents?