Lesson 7 of 50 – Creating Collections in MongoDB
14%

Creating Collections in MongoDB

A collection in MongoDB is a group of documents. It is similar to a table in a relational database, but documents in a collection can have different fields and structures. In this lesson, you will learn how to create, view, rename, and delete collections.

1. What Is a Collection?

A collection stores related documents inside a MongoDB database. Each document contains field-value pairs.

For example, a school database might contain:

school_db
    |
    |-- students
    |-- teachers
    |-- courses
    |-- fees

Here, students, teachers, courses, and fees are collections.

Example documents in the students collection:

{
    "name": "Rahul",
    "age": 20,
    "course": "ADCA"
}

{
    "name": "Priya",
    "course": "Web Development",
    "city": "Patna"
}

These documents have different fields, demonstrating MongoDB's flexible document structure.

2. Select a Database

Before creating a collection, select the database in which you want to create it.

use school_db

Check the current database:

db

Expected output:

school_db
Selecting a database does not necessarily create it permanently. MongoDB creates the database when a collection or data is stored in it.

3. Create a Collection Using createCollection()

MongoDB provides the createCollection() method to create a collection explicitly.

Syntax:

db.createCollection("collection_name")

Example:

db.createCollection("students")

If successful, MongoDB returns a result indicating that the collection was created.

You can create another collection:

db.createCollection("teachers")

Both collections belong to the currently selected school_db database.

4. Create a Collection Automatically

You do not always need to create a collection explicitly. MongoDB can create it automatically when you insert the first document.

Example:

db.employees.insertOne({
    name: "Amit",
    age: 25,
    department: "IT"
})

If the employees collection does not exist, MongoDB creates it as part of the insert operation.

This is a convenient way to create a collection and add its first document in one operation.

5. Display All Collections

Use show collections to display collections in the current database.

show collections

For example, the output might include:

employees
students
teachers

Only collections visible to your database user will be displayed.

6. Insert Documents into a Collection

After creating a collection, you can insert documents using insertOne() or insertMany().

Insert one document:

db.students.insertOne({
    student_id: 101,
    name: "Rahul",
    course: "ADCA",
    feesPaid: 5000
})

Insert multiple documents:

db.students.insertMany([
    {
        student_id: 102,
        name: "Amit",
        course: "Python"
    },
    {
        student_id: 103,
        name: "Priya",
        course: "Web Development"
    }
])

Display the inserted documents:

db.students.find()

MongoDB generates an _id field for each inserted document if you do not provide one.

7. Check Whether a Collection Exists

You can inspect collection names in the current database using the getCollectionNames() method.

db.getCollectionNames()

It returns an array of collection names that are visible to your database user.

Example output:

[
    "students",
    "teachers",
    "employees"
]

To check whether a specific collection exists, you can use:

db.getCollectionNames().includes("students")

The expression returns true if the collection name is present in the returned array.

8. Rename a Collection

MongoDB provides the renameCollection() method to change a collection's name.

Syntax:

db.old_name.renameCollection("new_name")

Example:

db.students.renameCollection("student_records")

This renames the students collection to student_records in the current database.

Verify the change:

show collections
If a collection with the destination name already exists, the rename operation may fail unless you explicitly choose an appropriate supported option. Check the destination before renaming.

9. Delete a Collection

The drop() method removes a collection and its documents.

Syntax:

db.collection_name.drop()

Example:

db.students.drop()

If the operation succeeds, MongoDB removes the students collection.

Verify the remaining collections:

show collections
Warning: Dropping a collection removes its documents and collection-specific structures such as indexes. Do not run this command on important data unless you intend to remove it.

10. Complete Practical Example

Let's create a collection for a computer training institute. Run these commands one by one in MongoDB Shell.

Step 1: Select the database

use soopro_db

Step 2: Create a collection

db.createCollection("courses")

Step 3: Insert course information

db.courses.insertMany([
    {
        course_name: "ADCA",
        duration_months: 12,
        fee: 10500
    },
    {
        course_name: "Web Development",
        duration_months: 6,
        fee: 10000
    },
    {
        course_name: "Tally Prime",
        duration_months: 3,
        fee: 4000
    }
])

Step 4: Display all collections

show collections

Step 5: Display course documents

db.courses.find()

You have now created a collection and inserted multiple documents into it.

11. Practice Assignment

  1. Select a database named college_db.
  2. Create a collection named students.
  3. Create another collection named teachers.
  4. Insert three student documents.
  5. Display all collection names.
  6. Check whether the students collection exists.
  7. Rename a practice collection from students to student_records.
  8. Create a temporary collection and practise deleting it with drop().

Use test data for rename and delete practice so that you do not accidentally remove important records.

🧠 Quick Quiz

Q1. Which method explicitly creates a collection?




Q2. Which command displays collections in the current database?




Q3. Which method removes a collection?