MongoDB Create Collection

MongoDB is a NoSQL database so data is stored in collection instead of table. createCollection method is used to create a collection in MongoDB.

Example

Create a collection named “employees”.

Create a js file named “employees.js”, having the following data:

var MongoClient = require('mongodb').MongoClient;  

var url = "mongodb://localhost:27017/ MongoDatabase";  

MongoClient.connect(url, function(err, db) {  

if (err) throw err;  

db.createCollection("employees", function(err, res) {  

if (err) throw err;  

console.log("Collection is created!");  

db.close();  

});  

}); 

    Open the command terminal and run the following command:

    Node employees.js  
    Node.js Create collection 1

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *