Geek Slack

MongoDB Tutorial
About Lesson



MongoDB mongosh Create Collection


MongoDB mongosh Create Collection

Introduction

Learn how to create a MongoDB collection using the mongosh shell interface.

Connecting to MongoDB

Before creating a collection, ensure you are connected to your MongoDB server:

Example: Connecting to MongoDB

mongosh

This command starts the mongosh shell and connects to the default MongoDB server running locally.

Switching to a Database

To create a collection, switch to the desired database using the use command:

Example: Switching to a Database

use mydatabase

This command switches to the “mydatabase” database. Replace mydatabase with your database name.

Creating a Collection

To create a new collection in MongoDB, use the createCollection method:

Example: Creating a Collection

db.createCollection("mycollection")

This command creates a new collection named “mycollection” within the current database.

Verifying Collection Creation

Verify that the collection has been created by listing all collections in the database:

Example: Listing Collections

show collections

This command lists all collections in the current database. Your newly created collection should appear in the list.

Conclusion

Creating a MongoDB collection using mongosh is straightforward. After creating the collection, you can start inserting documents to store data.

Join the conversation