Create a Database in MongoDB

In this Tutorial, you will learn how to create a database in mongodb for your project. So, let's get started!

Create databasae using MongoDB Shell

1. Open your terminal and run the MongoDB shell using the mongo command.

2. If you want to create the database in a specific location, you can switch to the admin database using the use command. For example, to switch to the admin database:

use admin

3. Use the use command to create a new database. If the database does not exist, MongoDB will create it. For example, to create a database called "mydatabase":

4. You can verify the currrent database by running this command

db

Create database using a MongoDB Driver

If you're working with a MongoDB driver in a programming language like Node.js, you can create a database as follows

1. First, install the MongoDB driver for your chosen programming language. In Node.js, you can use the mongodb package.

npm install mongodb
        

3. Use the MongoDB driver to connect to your MongoDB server. Provide the connection string, which includes the server address and authentication credentials.

const { MongoClient } = require('mongodb');

const uri = "mongodb://localhost:27017"; // MongoDB server address
const client = new MongoClient(uri);

async function main() {
  try {
    await client.connect(); // Connect to the MongoDB server
    console.log("Connected to MongoDB");

    const database = client.db("mydatabase"); // Specify the database name
    console.log("Database created");
  } finally {
    await client.close(); // Close the connection
  }
}

main().catch(console.error);