Create Database

To create a database in MongoDB, First create a MongoClient object and specify a connection URL with the correct ip address and the name of the database which you want to create.

Note
Note: MongoDB will automatically create the database if it does not exist, and make a connection to it.

Example

Create a folder named "MongoDatabase" as a database. Suppose you create it on Desktop. Create a js file named "createdatabase.js" within that folder and having the following code:

snippet
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MongoDatabase";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

Now open the command terminal and set the path where MongoDatabase exists. Now execute the following command:

snippet
Node createdatabase.js
Node.js Create database 1

Now database is created.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents