How to create new database in mongodb
To create a new database in MongoDB, you can use the following methods:
Method 1: Using the MongoDB Shell
- Open the MongoDB shell by running the command
mongo
in your terminal or command prompt. - Once you're in the shell, type the following command to create a new database:
use <database_name>
Replace
<database_name>
with the name of the database you want to create.
For example:
use mydatabase
This will create a new database named mydatabase
if it doesn't already exist.
Method 2: Using the MongoDB Compass GUI
- Open MongoDB Compass, a GUI tool for interacting with MongoDB.
- Click on the "Databases" tab in the left-hand menu.
- Click on the "Create Database" button.
- Enter the name of the database you want to create in the "Database name" field.
- Click on the "Create" button to create the database.
Method 3: Using the MongoDB Command-Line Tool
- Open a terminal or command prompt and navigate to the directory where your MongoDB installation is located.
- Run the following command to create a new database:
mongod --dbpath <path_to_database> --create <database_name>
Replace
<path_to_database>
with the path where you want to store the database files, and<database_name>
with the name of the database you want to create.
For example:
mongod --dbpath /data/db --create mydatabase
This will create a new database named mydatabase
in the /data/db
directory.
Method 4: Using a programming language
You can also create a new database using a programming language such as Python, Java, or Node.js. For example, in Python, you can use the pymongo
library to create a new database:
from pymongo import MongoClient
client = MongoClient()
db = client["mydatabase"]
This will create a new database named mydatabase
if it doesn't already exist.
Note: Before creating a new database, make sure you have MongoDB installed and running on your system.