Node.js Tutorial

Node.js MongoDB Create Collection

Node.js MongoDB Create Collection

Node.js MongoDB: Create Collection

MongoDB stores data in collections rather than tables. This guide shows you how to create a new collection from Node.js using the official MongoDB driver and the createCollection() method.

Node.js Tutorial:-
Complete Python Course:-

Install the MongoDB Driver

npm install mongodb

Example: Create the “employees” Collection

// employees.js
const { MongoClient } = require('mongodb');
const url = "mongodb://localhost:27017";
const dbName = "MongoDatabase";

MongoClient.connect(url, function(err, client) {
  if (err) throw err;
  const db = client.db(dbName);
  db.createCollection("employees", function(err) {
    if (err) throw err;
    console.log("Collection is created!");
    client.close();
  });
});

Run the Script

node employees.js
# Output: Collection is created!

Modern async/await Version

const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient("mongodb://localhost:27017");
  await client.connect();
  const db = client.db("MongoDatabase");
  await db.createCollection("employees");
  console.log("Collection created!");
  await client.close();
}
run().catch(console.error);

Note: Implicit Creation

MongoDB creates a collection automatically when you insert the first document ÔÇö explicit createCollection() is only needed for options like capped collections, validation, or specific indexes.

Download New Real Time Projects:- Click here
Complete Advance AI topics:-

Conclusion

Creating MongoDB collections in Node.js is a one-line call to createCollection(). Prefer async/await for modern code and remember MongoDB auto-creates collections on first insert. For more tutorials, stay tuned to .

mongodb create collection example
how to create collection in mongodb using node js mongoose
mongodb create collection if not exists
create collection mongodb shell
mongodb create collection with index
how to create collection in mongodb atlas
node js mongodb create collection example
nodejs mongodb express

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

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

Chat with us