How To Create A Table In MongoDB Using Node js

How To Create A Table In MongoDB Using Node js

How To Create A Table In MongoDB Using Node js

Emmanuel Ighosewe
Author
Emmanuel Ighosewe

MongoDB is a document-oriented database (open-source) that has been developed to store large amounts of data and enables you to work efficiently with the data. It refers to a NoSQL database (not just SQL) because storing and retrieving data in MongoDB is not table form.

MongoDB.Inc developed and managed the database under the SSPL (Server Side Public License), and it was first released in February 2009. It also offers official driver support for all major languages, such as Engine, Go, C, C++, C#, .Net, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Swift, and Mongoid. Therefore, you can use any of these languages ​​to build applications. Many companies now use MongoDB, some of them are Facebook, Nokia, eBay, Adobe, Google, etc., to store your large scale of data.

How it works

The MongoDB environment provides a server that can be started and use MongoDB to create various databases on it.

Thanks to the NoSQL database, data is stored in collections and documents. Databases, collections, and documents are therefore interlinked.

The MongoDB database has collections like the MYSQL database has tables. You can create multiple databases and collections.

We now have documents in our collection. These documents have the data we need to store in the MongoDB database, and a collection can contain different documents and has no schema, which means that one document does not have to look like another.

With fields, you can create Documents. Fields are known as key-value combinations in the documents, same with the columns in the relation database. Field values ​​can be any type of BSON data, such as Double, String, Boolean, etc.

MongoDB stores data in BSON document format. Here, BSON represents the binary representation of the JSON document. In other words, the MongoDB server converts JSON data into a binary format called BSON on the back end and can store and query BSON more efficiently.

You can store nested data in MongoDB documents. This kind of data nesting enables you to create complex relationships between data and store them in the same document, making working and retrieving data very efficient compared to SQL. In SQL, it is necessary you write complex connections to fetch the data from the first and second tables. The maximum size of the BSON document you can have is 16MB.

Why Use MongoDB?

There are many advantages attached to using MongoDB; the following are a few of them;

  • Document Oriented: Because MongoDB is a NoSQL database, it does not store data in a relational format but in documents. This increases the flexibility of MongoDB and can adapt to real-world business conditions and requirements.
  • Ad-hoc query: MongoDB supports field search, range query, and regular expression search. You can run queries to return specific fields in the document.
  • Indexing: You can create indexes to improve search performance in MongoDB. You can index any field in a MongoDB document.
  • Replication: MongoDB can offer high availability through replication. A replica set contains two or more Mongo database instances. Any member of the replica may take on a set of primary or secondary replica roles at any time. The Primary replica is the main server that interacts with the client and handles all read/write operations. The secondary replicas use internal replication to retain a copy of the primary data. Suppose the primary replica fails; in that case, the replica set switches automatically to the secondary server and then reverts to the primary server.

NodeJS MongoDB Create Collection

Before you can create a collection in MongoDB, start by creating a MongoClient object, then a link URL containing the correct IP address and the name of the database should be defined.

Step 1: Start MongoDB

If you want to start the MongoDB Service, enter the code below.

sudo service mongoid start

Step 2: Get the base URL of the MongoDB Service

If you want to locate the base URL of MongoDB, open a Terminal and launch Mongo Shell.

Upstack@nodejs:~$ mongo

MongoDB shell version v3.4.9

connecting to: mongodb://127.0.0.1:27017

MongoDB server version: 3.4.9

The server has startup warnings:

2021-10-29T18:15:36.110+0530 I STORAGE [initandlisten]

The MongoDB base URL IS returned back by the Mongo Shell when starting up.

mongodb://127.0.0.1:27017

Step 3: Prepare the complete URL

Ensure you have the complete URL. To the base URL, attach the name of the database you want to build (newdb).

mongodb://127.0.0.1:27017/newdb

Step 4: Create a MongoClient

You can now create a MongoClient object that can be bound to a MongoDB deployment. This step is crucial if you want to connect MongoDB and NodeJS together.

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

Step 5: Binding To Server

Using the URL, bind MongoClient to the MongoDB Server.

MongoClient.connect(mongodb://127.0.0.1:27017/newdb, function(err, db));

Provided the relationship is good, the db object points to a newly created newdb.

Step 6: Create a MongoDB Set

Following is the syntax of the createCollection() function, which is used in building collections in MongoDB from NodeJS.

db.createCollection(<collection_name>,<callback_function>)

collection_name – The name of the newly created MongoDB Collection that we are making

callback_function – After Node tries to build a list and is ready to output, this NodeJS call function is renamed.

Example:

After listing some of the important steps required in creating TABLE in the MongoDB database, then we can start the compilation.

// Script.js

// we create 'users' collection in newdb database

var url = "mongodb://localhost:27017/newdb";

// create a client to mongodb

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

// make client connect to mongo service

MongoClient.connect(url, function(err, db) {

if (err) throw err;

// db pointing to newdb

console.log("Switched to "+db.databaseName+" database");

// create 'users' collection in newdb database

db.createCollection("users", function(err, result) {

if (err) throw err;

console.log("Collection is created!");

// close the connection to db when you are done with it

db.close();

});

});

Output:

upstack@upstack:~/workspace/nodejs/mongodb$ node script.js

Switched to newdb database

The collection is created!



We are growth pros. CONTACT US so we can help you scale your team with top 1% talent worldwide!