Create MongoDB Collection

MongoDBBeginner
Practice Now

Introduction

In this lab, you will learn the fundamental steps of working with MongoDB. You will use the MongoDB Shell (mongosh) to create a database, add a collection, insert documents, and perform basic data management operations. This hands-on approach will provide you with practical experience in core MongoDB commands, establishing a solid foundation for more advanced database tasks.

Start MongoDB Shell and Create a Database

Your first step is to connect to the MongoDB server using its interactive shell, mongosh. This tool allows you to execute commands directly against your database instance.

In your terminal, start the MongoDB Shell by running the mongosh command.

mongosh

You will see a connection message, indicating you are now in the mongosh environment.

Current Mongosh Log ID: 65a7f3e8f5a8a9b3c4d5e6f7
Connecting to:           mongodb://127.0.0.1:27017/
Using MongoDB:           8.0.2
Using Mongosh:           2.2.6
...
test>

The test> prompt indicates you are currently connected to the default test database. Let's switch to a new database for our project. In MongoDB, you can switch to a database that does not yet exist. It will be created automatically when you first store data in it.

Use the use command to switch to a new database named my_store.

use my_store

The shell will confirm the switch.

switched to db my_store

To confirm which database you are currently using, you can type db.

db;

The output will show the name of the current database.

my_store

Create a Collection and Insert a Document

Now that you are in the my_store database, the next step is to create a collection. A collection is a group of MongoDB documents, similar to a table in a relational database.

Let's create a collection named products. You can do this explicitly with the createCollection() method.

db.createCollection("products");

A successful operation will return an object indicating success.

{ ok: 1 }

You can list all collections in the current database to verify that products was created.

show collections
products

With the collection created, you can now insert your first document. A document is a BSON object, which is a binary-encoded serialization of JSON-like documents.

Use the insertOne() method to add a single document to the products collection.

db.products.insertOne({
  name: "Laptop",
  price: 1200,
  category: "Electronics"
});

MongoDB will confirm the insertion and provide the unique _id of the new document.

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

This ObjectId is automatically generated for each document and serves as its primary key.

Insert Multiple Documents

Often, you will need to add multiple documents to a collection at once. MongoDB provides the insertMany() method for this purpose. This method is more efficient than calling insertOne() multiple times.

Let's add two more products to our products collection. The insertMany() method takes an array of document objects as its argument.

db.products.insertMany([
  {
    name: "Keyboard",
    price: 75,
    category: "Electronics"
  },
  {
    name: "Desk Chair",
    price: 150,
    category: "Furniture"
  }
]);

The output will confirm that the operation was acknowledged and will list the _id values for each of the newly inserted documents.

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

Now, let's check the total number of documents in the products collection. You can use the countDocuments() method for this.

db.products.countDocuments();

The shell should return 3, reflecting the one document from the previous step and the two you just added.

3

Query and View Documents

After inserting data, you will want to retrieve and view it. The primary method for querying a collection is find().

To view all documents in the products collection, run the find() method without any arguments.

db.products.find();

The mongosh shell automatically formats the output for readability, displaying all three documents in your collection.

[
  {
    _id: ObjectId("..."),
    name: 'Laptop',
    price: 1200,
    category: 'Electronics'
  },
  {
    _id: ObjectId("..."),
    name: 'Keyboard',
    price: 75,
    category: 'Electronics'
  },
  {
    _id: ObjectId("..."),
    name: 'Desk Chair',
    price: 150,
    category: 'Furniture'
  }
]

The find() method can also accept a query document to filter the results. This allows you to find documents that match specific criteria. For example, let's find all products in the "Electronics" category.

db.products.find({ category: "Electronics" });

This command will return only the documents where the category field has the value "Electronics".

[
  {
    _id: ObjectId("..."),
    name: 'Laptop',
    price: 1200,
    category: 'Electronics'
  },
  {
    _id: ObjectId("..."),
    name: 'Keyboard',
    price: 75,
    category: 'Electronics'
  }
]

This simple filtering capability is a powerful feature for retrieving specific data from your collections.

Drop a Collection

In the final step, you will learn how to remove a collection from a database. This operation is irreversible and deletes the collection and all of its documents and indexes. It is useful for cleaning up temporary data or removing obsolete collections.

To demonstrate this, let's first create a temporary collection.

db.createCollection("temp_data");
{ ok: 1 }

Now, use the drop() method on the temp_data collection to remove it.

db.temp_data.drop();

The command will return true if the collection was successfully dropped.

true

To verify that the collection has been removed, you can list all collections in the database again.

show collections

The output will now only show the products collection, confirming that temp_data has been deleted.

products

This concludes the basic operations for managing collections in MongoDB. Remember to exit the mongosh shell when you are finished.

exit;

Summary

In this lab, you have learned the fundamental skills for working with MongoDB. You started by connecting to a MongoDB instance using the mongosh shell. You then practiced creating a database and a collection, inserting both single and multiple documents, and querying for that data using the find() method. Finally, you learned how to safely remove a collection using the drop() command. These core operations—Create, Read, and Delete—are the building blocks for any application that uses MongoDB as its data store. You are now equipped with the basic knowledge to manage data in a MongoDB environment.