0
0
MongoDBquery~5 mins

Database and collection creation in MongoDB

Choose your learning style9 modes available
Introduction

We create databases and collections to organize and store data in MongoDB. This helps keep data neat and easy to find.

When starting a new project and you need a place to save your data.
When you want to separate different types of data, like users and products.
When you want to prepare your database before adding any data.
When you want to create a special collection with specific settings.
Syntax
MongoDB
use databaseName

db.createCollection('collectionName')

use databaseName switches to or creates a database.

db.createCollection() makes a new collection inside the current database.

Examples
This switches to the myShop database and creates a products collection.
MongoDB
use myShop

db.createCollection('products')
This switches to the school database and creates a students collection.
MongoDB
use school

db.createCollection('students')
This switches to testDB. The database is created when you add data or collections.
MongoDB
use testDB

// No collection created yet, but database is ready
Sample Program

This example creates a database called library and a collection called books. Then it lists all collections in the current database.

MongoDB
use library

db.createCollection('books')

show collections
OutputSuccess
Important Notes

Databases and collections are created lazily in MongoDB. They appear only after you insert data or explicitly create collections.

You don't have to create collections manually; MongoDB creates them automatically when you insert documents.

Summary

Use use databaseName to switch or create a database.

Use db.createCollection('collectionName') to make a new collection.

Collections organize your data inside databases.