Dark Mode
Image

Node.js 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:

Backward Skip 10sPlay VideoForward Skip 10s

  1. var MongoClient = require('mongodb').MongoClient;  
  2. var url = "mongodb://localhost:27017/ MongoDatabase";  
  3. MongoClient.connect(url, function(err, db) {  
  4. if (err) throw err;  
  5. db.createCollection("employees", function(err, res) {  
  6. if (err) throw err;  
  7. console.log("Collection is created!");  
  8. db.close();  
  9. });  
  10. });  

Open the command terminal and run the following command:

  1. Node employees.js  

Node.js Create collection 1

Now the collection is created.

Comment / Reply From