Create Db in MongoDB
Creating a database in MongoDB is a simple process. MongoDB is schema-less and automatically creates a new database when you insert your first document into a collection within that database. You do not need to explicitly create the database beforehand.
However, you can explicitly create a database and work with it through the MongoDB shell or programmatically using one of MongoDB's drivers (like Node.js, Python, etc.).
Here’s a step-by-step guide for both methods.
1. Create a Database in MongoDB (Using MongoDB Shell)
To create a new database, follow these steps:
Step 1: Start the MongoDB Shell
If you're not already in the MongoDB shell, start it by running the mongo command in your terminal:
$ mongo
This will connect to the default local MongoDB server.
Step 2: Use a New Database
In MongoDB, the database is created implicitly when you insert data. However, to switch to a specific database (or create one), use the use command. This doesn’t actually create the database until you insert the first document.
use myNewDatabase
This switches to the database myNewDatabase. If it doesn’t exist yet, MongoDB will create it when you add data.
Step 3: Create a Collection and Insert Data
Now that you've selected your database, create a collection and insert your first document. This will automatically create the database if it doesn't already exist.
db.myCollection.insertOne({ name: "Alice", age: 30 })
Here, you’re inserting a single document with fields name and age into a collection called myCollection. At this point, MongoDB will create the database myNewDatabase if it was previously non-existent.
Step 4: Verify the Database
To verify that the database was created, list all databases:
show databases
This will show a list of databases, and you should see myNewDatabase in the list.
2. Create a Database Programmatically (Using Node.js)
If you're using MongoDB with Node.js, you can also create a database by connecting to MongoDB and inserting data into a collection.
Step 1: Install MongoDB Node.js Driver
If you don’t have it installed, install the MongoDB Node.js driver using npm:
npm install mongodb
Step 2: Create a Database and Insert Data
Here is a simple example in Node.js to create a new database and insert a document:
const { MongoClient } = require('mongodb');// Replace with your MongoDB URIconst uri = "mongodb://localhost:27017"; // Default URI for a local MongoDB serverasync function createDatabase() { const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { await client.connect(); // Choose a database (it will be created when data is inserted) const db = client.db("myNewDatabase"); // Insert a document into a collection (this will create the collection and database) const result = await db.collection("myCollection").insertOne({ name: "Alice", age: 30 }); console.log(`Document inserted with _id: ${result.insertedId}`); } finally { await client.close(); }}createDatabase().catch(console.error);
In this example:
- The
MongoClientconnects to the MongoDB server. - The
db()method switches to themyNewDatabasedatabase. If it doesn’t exist, it will be created. - The
insertOne()method inserts a document into themyCollectioncollection. This action will create the collection if it doesn’t already exist.
3. Create a Database in MongoDB Atlas
If you're using MongoDB Atlas, MongoDB's managed cloud service, the process of creating a database is also simple, but you will need to do it through the Atlas interface.
Steps:
- Sign in to MongoDB Atlas at https://cloud.mongodb.com/.
- Select your project or create a new project.
- In the left-hand navigation pane, go to Clusters and select your cluster.
- Click on the Collections tab.
- Click Create Database.
- Provide the name for the database and the first collection you'd like to create within that database.
- Click Create Database.
This will create your new database and collection in MongoDB Atlas.
Summary
- In MongoDB, you do not need to explicitly create a database. When you insert the first document into a collection, MongoDB automatically creates both the database and the collection.
- You can use the
use <databaseName>command to switch to a database. - You can also create a database and insert data programmatically using various drivers like Node.js or others.
- In MongoDB Atlas, you can create a database and collection through the Atlas user interface.
MongoDB's flexibility allows you to start working with databases and collections without having to worry about predefined schemas or structures.