In MongoDB, databases are created on-demand when you insert the first document into a collection. There's no separate command to explicitly create a database. However, you can connect to MongoDB and create a collection using Node.js, which implicitly creates the database if it doesn't already exist.
Here's how to achieve this:
1. Install MongoDB Driver:
Open your terminal or command prompt and make sure you have npm (Node Package Manager) installed. Then, use npm to install the official MongoDB Node.js driver:
npm install mongodb
2. Connect and Create Collection:
Create a Node.js file (e.g., create_database.js) and use the following code to connect to MongoDB and create a collection:
const { MongoClient } = require('mongodb');
const uri = "mongodb://your_connection_string"; // Replace with your actual connection string
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect((err) => {
if (err) {
console.error(err);
return;
}
console.log("Connected to MongoDB!");
const db = client.db("your_database_name"); // Replace with your desired database name
// Create a collection (implicitly creates the database if it doesn't exist)
db.collection("your_collection_name").insertOne({}, (err, result) => {
if (err) {
console.error(err);
return;
}
console.log("Collection created!");
client.close();
});
});
Explanation:
-
We require the
MongoClientclass from the MongoDB driver. -
The
urivariable holds your MongoDB connection string, including hostname, port, username, and password (if applicable). -
We connect to MongoDB using
MongoClientand handle any errors. -
The
dbobject is obtained usingclient.db(), specifying the desired database name. -
We create a collection using
db.collection()and insert an empty document ({}) withinsertOne(). This triggers the creation of the collection and implicitly creates the database if it doesn't exist. -
We close the connection after successful collection creation.
Remember:
-
Replace
"your_connection_string"with your actual MongoDB connection details. -
Modify
"your_database_name"and"your_collection_name"to your preferred names.
This code establishes a connection, creates a collection (implicitly creating the database), and closes the connection.