Create COLLECTION in mongodb using node.js –

If there is a database ‘db2’ in your mongodb and you want to create a collection ‘students’ inside this database; use the following code-

//to import mongodb 
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/db2";
//make client connect 
MongoClient.connect(url, function (err, client) {
    var db = client.db('db2');
    if (err) throw err;
    //students is a collection we want to create inside db2                            
    db.createCollection("students", function (err, res) {
        if (err) throw err;
        console.log("Collection created!");

Write this code in your editor and save with js extension and run this at your terminal.
(I have saved above code with createcollection.js)

Run Command

C:\Users\Your Name>node createcollection.js

You can see the “Collection created!” message at console log.


Collection created!

That means your Collection has been created. To see this Collection you need to open mongobooster and referesh your localhost.

(Here, we have created collection ‘students’ inside the database ‘db2’).

Learn More-