NodeJS MongoDB Create Collection

MongoDB Create Collection Thumbnail

A Collection is used to store one or many MongoDB documents. A Collection is similar to a table in a relational database. A relational database such as MySQL database has multiple tables to store different kinds of data similarly a MongoDB database has multiple collections to group different kinds of documents together but unlike a relational database, it doesn’t store data in rows and columns. Multiple collections can be created inside a database.

Creating a MongoDB Collection with NodeJS

MongoClient has a method connect() which takes a URI and a callback as an argument. URI is a MongoDB connection string used to connect to the MongoDB database and a callback is a function that returns the error or the client object. 

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
    // callback body
});

If you find the above code confusing, we recommend reading our previous tutorial where we have covered the entire process of creating a database.

This client object has a method db() that takes the name of a database as an argument to create a database object.

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db(databaseName);
});

This database object can use the method createCollection() to create a new collection.

database.createCollection(collectionName, function (err, client) {
    // callback body
});

The complete code snippet for creating a collection is:

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db(databaseName);

  database.createCollection(collectionName, function (err, client) {
    // callback body
  });
});

where,

  • databaseName is the name of a database in which you want to create a collection,
  • database is a database object,
  • collectionName is the name of the collection you want to create

Alternate Method for Creating a MongoDB Collection

The above method might be complex for a new developer so here is an easy way of creating a collection.

You can pass the database name in which you want to create a collection in the connection string(URI) at the end after a slash(“/”). Then inside the callback, you can directly call the createCollection() method using the database object.   

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/databaseName", function(err, db) {
  if (err) throw err;
  db.createCollection(collectionName, function(err, res) {
    // callback body
  });
});

where,

  • databaseName is the name of a database in which you want to create a collection,
  • db is a database object,
  • collectionName is the name of the collection you want to create

Example of Creating a MongoDB Collection

Let’s see an example of creating a collection.

Project Structure: We need a folder that contains a file “app.js”, where we will write our code.

Locate the project folder in a terminal and execute the below command to initiate NPM to install the MongoDB module.

npm init -y
Initialise NPM

Install the MongoDB module.

npm i mongodb
Install MongoDB 1

Inside the “app.js” file import the MongoClient from the MongoDB module.

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

Then use the connect() method to pass a URI and then inside the callback use the client object to use the db() method and pass “newdatabase” as a database name which we have created in our previous tutorial.

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db("newdatabase");
});

Finally, use the create createCollection() method to pass a collection name to create it, and inside the callback check for the error, throw the error if occur, then log the successful message in the console and close the client.

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db("newdatabase");

  database.createCollection("newcollection", function (err, res) {
    if (err) throw err;
    console.log("Collection created!");
    db.close();
  });
});

Complete Code:

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db("newdatabase");

  database.createCollection("newcollection", function (err, res) {
    if (err) throw err;
    console.log("Collection created!");
    client.close();
  });
});

Output:

Output 5

Using MongoDB Compass to Verify Collection Creation

A collection can’t be created whenever you try to create it without any data. To see the result you have to insert some data into the collection.

After inserting the data, you can verify that the collection is successfully created by using MongoDB Compass which provides a graphical way to interact with the MongoDB database.

Open the MongoDB Compass and enter the MongoDB URI and press enter.

Collection Created

Here you can see that the collection name “newcollection ” has been created inside the database name “newdatabase”.

Summary

A relational database like MySQL uses tables to store data in the form of rows and columns whereas a MongoDB database used collection to store documents that have different fields. We can create a collection inside a database using the createCollection() method. Hope this tutorial helps you to understand the process of creating a collection in a MongoDB database using NodeJS.

Reference

https://www.mongodb.com/docs/manual/reference/method/db.createCollection/