Node.js MongoDB Create Collection

Node.js MongoDB Create Collection

MongoDB is a popular NoSQL database where data is stored in collections instead of traditional tables. In this guide, we’ll see how to create a collection in MongoDB using Node.js. The createCollection() method is used to create a new collection within a specified database.

Data Science Tutorial:–Click Here

Example: Create a Collection Named “employees”

Let’s create a simple Node.js script to add a new collection called employees in our MongoDB database.

  1. Create a JavaScript file named employees.js and add the following code:

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();  
  });  
});  

  1. Run the Script
    Open your terminal or command prompt and execute the following command:

Introduction to Applied AI:–Click Here

node employees.js

Once executed, you’ll see the message “Collection is created!” confirming that your MongoDB collection has been successfully created.

Download New Real Time Projects :–Click here
SQL Tutorial :–Click Here
Deep Learning Tutorial:– Click Here
Machine Learning Tutorial:–Click Here
Complete Advance AI topics:- CLICK HERE
Complete Python Course with Advance topics:-Click Here


mongodb create collection example how to create collection in mongodb using node js mongoose mongodb create collection if not exists how to create collection in mongodb compass create collection mongodb shell mongodb create collection with index how to create collection in mongodb atlas mongodb create collection with unique index node js mongodb create collection example node js mongodb create collection github mongodb create collection, create collection, populate collections in mongodb, nodejs mongodb, connect mongodb with nodejs, complete nodejs express mongodb curd, node js mongodb connection, mix nodejs mongodb, how to connect mongodb in nodejs, create new collections, nodejs mongodb express, mongodb collections tutorials, mongodb nodejs, how to connect mongodb with nodejs, how to connect nodejs app to mongodb, how to create mongodb schemas and data models, linking collections in mongodb

Share this content:

Post Comment