Friday, 13 November 2020

How to Create the Database and Collection in MongoDB? | MongoDB Tutorial for Beginners

🚀 Start Your MongoDB Journey with Ram N Java!

Ready to build your first NoSQL database? Subscribe now for high-quality, beginner-friendly tech tutorials that make complex database setup and management simple to master!

🔔 SUBSCRIBE FOR FREE NOW

Creating Databases and Collections in MongoDB

The first step in any MongoDB project is setting up your storage structure. Unlike traditional relational databases that require strict schemas upfront, MongoDB is flexible. However, you still need to know how to initialize your Databases and Collections to start storing data.

1. Creating a Database

In MongoDB, you don't use a "create" command for databases. Instead, you use the use command. If the database doesn't exist yet, MongoDB will create it for you the moment you save data into it.

// Switch to (or create) a database named 'myNewDB' use myNewDB

2. Creating a Collection

Collections are the MongoDB equivalent of "tables." While MongoDB can create them automatically when you insert a document, you can also create them explicitly using the createCollection() method, which allows for extra configuration.

// Explicitly create a collection named 'users' db.createCollection("users")

Helpful Commands

  • db: Shows the name of the database you are currently using.
  • show dbs: Lists all existing databases (note: a new DB won't show up until it has data!).
  • show collections: Displays all collections within your current database.

💡 Quick Beginner Tip

Don't panic if you run show dbs and your new database isn't there! MongoDB follows a "lazy creation" policy. It won't actually allocate disk space for a database until you insert at least one document into a collection inside it.

Step Up Your MongoDB Skills:

1 comment:

Tutorials