Create MongoDB Collection

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn the fundamental steps of working with MongoDB, focusing on creating and managing databases and collections using the MongoDB Shell (mongosh). You'll explore how to launch the MongoDB Shell, create a new database, add a collection, insert sample documents, and perform basic collection management operations.

Through a hands-on approach, you'll gain practical experience with essential MongoDB commands such as use, createCollection(), insertOne(), insertMany(), and drop(). By the end of this lab, you'll have a solid understanding of how to perform basic Create, Read, Update, and Delete (CRUD) operations in MongoDB, setting a strong foundation for more advanced database interactions.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/DataTypesGroup(["`Data Types`"]) mongodb/BasicOperationsGroup -.-> mongodb/start_mongodb_shell("`Start MongoDB Shell`") mongodb/BasicOperationsGroup -.-> mongodb/create_database_collection("`Create Database and Collection`") mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/BasicOperationsGroup -.-> mongodb/delete_document("`Delete Document`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/DataTypesGroup -.-> mongodb/use_string_data_types("`Use String Data Types`") subgraph Lab Skills mongodb/start_mongodb_shell -.-> lab-420695{{"`Create MongoDB Collection`"}} mongodb/create_database_collection -.-> lab-420695{{"`Create MongoDB Collection`"}} mongodb/insert_document -.-> lab-420695{{"`Create MongoDB Collection`"}} mongodb/delete_document -.-> lab-420695{{"`Create MongoDB Collection`"}} mongodb/find_documents -.-> lab-420695{{"`Create MongoDB Collection`"}} mongodb/use_string_data_types -.-> lab-420695{{"`Create MongoDB Collection`"}} end

Start MongoDB Shell

Welcome to the MongoDB Hands-on Lab! In this comprehensive tutorial, we'll explore MongoDB's fundamental operations using the MongoDB Shell (mongosh). This lab is designed to provide a practical, step-by-step introduction to database management with MongoDB.

MongoDB is a powerful, flexible NoSQL database that allows for dynamic and scalable data storage. Before we dive into the practical exercises, let's set up our environment and start exploring.

Open Terminal and Launch MongoDB Shell

To begin our MongoDB journey, we'll first launch the MongoDB Shell. This interactive environment allows us to directly interact with our MongoDB database using commands.

Open a terminal in your lab environment and launch the MongoDB Shell by running the mongosh command:

mongosh

MongoDB Shell Output:

Current Mongosh Log ID: 65a7f3e8f5a8a9b3c4d5e6f7
Connecting to:           mongodb://127.0.0.1:27017/
Using MongoDB:           7.0.2
Using Mongosh:           2.1.1

Explore Basic MongoDB Shell Commands

Let's start by listing the available databases in our MongoDB instance:

MongoDB Shell Input:

> show dbs

MongoDB Shell Output:

admin   40.00 KiB
config  12.00 KiB
local   40.00 KiB

These default databases are system databases that MongoDB creates automatically. In the following steps, we'll create our own database and collections.

Create Database and Collection

Now that we've launched the MongoDB Shell, let's learn how to create a new database and collection. In MongoDB, databases and collections are created dynamically when you first use them.

Switch to a New Database

We'll create a new database called university using the use command:

MongoDB Shell Input:

> use university

MongoDB Shell Output:

switched to db university

The use command creates a new database if it doesn't exist or switches to an existing database.

Create a Collection

Next, we'll create a collection named students within the university database:

MongoDB Shell Input:

> db.createCollection("students")

MongoDB Shell Output:

{ ok: 1 }

Verify Database and Collection

Let's confirm our current database and list its collections:

MongoDB Shell Input:

> db

MongoDB Shell Output:

university

MongoDB Shell Input:

> show collections

MongoDB Shell Output:

students

We've successfully created a new database and collection, setting the stage for our next operations.

Insert Sample Documents

In this step, we'll learn how to insert documents into our students collection. MongoDB uses a flexible, JSON-like document model, which allows for dynamic and varied data structures.

Insert a Single Document

We'll start by inserting a single student document using the insertOne() method:

MongoDB Shell Input:

> db.students.insertOne({
    name: "John Doe",
    age: 22,
    major: "Computer Science",
    gpa: 3.7
})

MongoDB Shell Output:

{
  acknowledged: true,
  insertedId: ObjectId("...")
}

Insert Multiple Documents

Now, let's insert multiple student documents using the insertMany() method:

MongoDB Shell Input:

> db.students.insertMany([
    {
        name: "Alice Smith",
        age: 21,
        major: "Data Science",
        gpa: 3.9
    },
    {
        name: "Bob Johnson",
        age: 23,
        major: "Software Engineering",
        gpa: 3.5
    }
])

MongoDB Shell Output:

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("..."),
    '1': ObjectId("...")
  }
}

Verify Inserted Documents

Let's confirm the number of documents and view their contents:

MongoDB Shell Input:

> db.students.countDocuments()

MongoDB Shell Output:

3

MongoDB Shell Input:

> db.students.find()

MongoDB Shell Output:

[
  {
    _id: ObjectId('674433d99d1e4f9235c1c18c'),
    name: 'John Doe',
    age: 22,
    major: 'Computer Science',
    gpa: 3.7
  },
  {
    _id: ObjectId('674433e09d1e4f9235c1c18d'),
    name: 'Alice Smith',
    age: 21,
    major: 'Data Science',
    gpa: 3.9
  },
  {
    _id: ObjectId('674433e09d1e4f9235c1c18e'),
    name: 'Bob Johnson',
    age: 23,
    major: 'Software Engineering',
    gpa: 3.5
  }
]

View Collection Status

Understanding your collection's status and characteristics is crucial for effective database management. In this step, we'll explore various methods to retrieve collection information.

Check Collection Statistics

Use the stats() method to get detailed information about the collection:

MongoDB Shell Input:

> db.students.stats()

MongoDB Shell Output:

{
  ns: 'university.students',
  count: 3,
  size: 456,
  avgObjSize: 152,
  storageSize: 16384,
  freeStorageSize: 0,
  capped: false,
  nindexes: 1,
  indexDetails: { _id_: { ... } },
  totalIndexSize: 16384,
  indexSizes: { _id_: 16384 },
  scaleFactor: 1
}

List Collection Information

Display basic information about the collection:

MongoDB Shell Input:

> db.students.dataSize()

MongoDB Shell Output:

456

MongoDB Shell Input:

> db.students.count()

MongoDB Shell Output:

3

View Collection Indexes

Check the indexes of the collection:

MongoDB Shell Input:

> db.students.getIndexes()

MongoDB Shell Output:

[
  {
    v: 2,
    key: { _id: 1 },
    name: '_id_',
    ns: 'university.students'
  }
]

Drop Test Collection

In this final step, we'll demonstrate how to drop (delete) a collection in MongoDB. This is useful when you want to remove an entire collection from your database.

Create a Test Collection

First, create a temporary collection to demonstrate the dropping process:

MongoDB Shell Input:

> use university

MongoDB Shell Output:

switched to db university

MongoDB Shell Input:

> db.createCollection("temp_students")

MongoDB Shell Output:

{ ok: 1 }

MongoDB Shell Input:

> db.temp_students.insertOne({name: "Test Student"})

MongoDB Shell Output:

{
  acknowledged: true,
  insertedId: ObjectId("...")
}

Drop the Collection

Use the drop() method to remove the temporary collection:

MongoDB Shell Input:

> db.temp_students.drop()

MongoDB Shell Output:

true

Verify Collection Removal

Confirm that the collection no longer exists:

MongoDB Shell Input:

> show collections

MongoDB Shell Output:

students

Congratulations! You've completed the MongoDB Hands-on Lab, learning key operations like creating databases, inserting documents, checking collection status, and dropping collections.

Summary

In this lab, you successfully learned the core skills of working with MongoDB through practical, hands-on experience. You started by launching the MongoDB Shell, creating a new database called "university", and adding a "students" collection. You then practiced inserting single and multiple documents using insertOne() and insertMany() methods, gaining insights into document creation and management.

You also explored important MongoDB operations like checking collection statistics, counting documents, and dropping collections. These fundamental skills provide a solid foundation for understanding database interactions, giving you the confidence to perform basic CRUD operations and manage MongoDB databases effectively. The step-by-step approach has equipped you with practical knowledge that can be applied in real-world database management scenarios.

Other MongoDB Tutorials you may like