In this tutorial you will learn about the Nodejs MongoDB Create Collection and its application with practical example.
Node.js MongoDB Create Collection
MongoDB is a NoSQL database and it stores data in form of collection instead of table. A MongoDB collection is simply created using the createCollection method.
Example :- Let’s create MongoDB Collection named as “employees”
Step 1:- Let’s, create a node_mongo_create_collection.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 |
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("W3Adda | MongoDB Collection is created!"); db.close(); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mongo_create_collection.js |
you will see following output on terminal –
Ooutput:-
1 |
W3Adda | MongoDB Collection is created! |