Fraud Blocker
  • Solution
    • Solution
      • Enteros – SaaS Database Solution
      • Enteros – Expert Services
    • Use Cases
      • DevOps
      • Monitoring Business Performance
      • IT Production Operations
      • Cloud Migration and Scaling
      • Continuous Delivery
      • NoSQL / MongoDB / Cassandra
    • Industries
      • Insurance
      • Social Media & Entertainment
      • Government
      • Financial Services
      • Healthcare
      • Retail
      • Telecom
    • Roles
      • IT Production Operations
      • CIO
      • Engineering Manager
      • CFO
  • Product
    • UpBeat
      • Database Performance Management SaaS
    • UpBeat Platform
      • Cloud Cost Waste Analyzer (vCore & Credit Optimization)
      • AiOps DB Analytical Engine for Anomaly and Root Causes Detection
      • Deep Workload Diagnostics for Oracle Systems
      • Remediation Engine for Oracle Infrastractures
      • UpBeat Labs
    • DPMDPM is an innovative platform for IT production database performance management. The first of its kind, DPM provides decision support for each stage of the performance problem lifecycle
      • Learn more
  • Company
    •  About
      • Overview
      • Blog
      • News
      • Management
      • Careers
      • Partners
    • Feature articleNPMD solutions play a key role in helping IT ops support increasingly complex technologies and services with network visibility, detection of performance issues and root cause analysis
      • Read more
    •  
  • Search
  • See Demo
  • Contact
(408) 824-1292

MongoDB Node.js

See Live Demo Start Free Trial

Preamble

​​

The most popular database management system for Node.js at the moment is MongoDB. To work with this platform, you must first install the server MongoDB itself. More details on how to do this are described here. Besides the Mongo server itself, we need a driver to interact with Node.js.

Start working with MongoDB Node.js

When connecting and interacting with databases in MongoDB we can distinguish the following steps:

  • Connecting to the server
  • Getting a database object on the server
  • Getting the collection object in the database
  • Interaction with the collection (add, delete, receive, modify data)
Read more"Indian Country" highlights Enteros and its database performance management platform *

So, let’s create a new project. To do this, define a new directory, which will be called mongoapp. Then let’s define a new file package.json in this directory:

{
"name": "mongoapp",
"version": "1.0.0",
"dependencies": {
"express": "^4.16.0",
"body-parser": "^1.18.0",
"mongodb": "^3.1.0"
}
}

In this case, the last dependency is “mongodb”, which represents the driver. All necessary background information on this particular driver can be found at mongodb.github.io/node-mongodb.

Then let’s go to this directory in the command line/terminal and execute the command to add all the necessary packages:

npm install

Connecting to the database

Read moreOracle AWR data storage and collection frequency optimization.

The key class for working with MongoDB is MongoClient class, and all interactions with the data warehouse will go through it. Accordingly, we must first get MongoClient:

const MongoClient = require("mongodb").MongoClient;

The connect() method is used to connect to the mongodb server:

const MongoClient = require("mongodb").MongoClient;

// create a MongoClient object and give it a connection string
const mongoClient = new MongoClient("mongodb://localhost:27017/", { useNewUrlParser: true });
mongoClient.connect(function(err, client){

if(err){
return console.log(err);
}
// interaction with database
client.close();
});

At first, the MongoClient object is created. To do this, two parameters are passed to its constructor. The first parameter is the server address. As the address protocol is set “mongodb://”. On the local machine, the address is localhost, after which the port number is specified. By default, the port number is 27017.

Read moreMongoDB profiler and database performance problem diagnosis and identification

The second pair is an optional configuration volume. MongoDb is constantly evolving. In this case, the configuration object is used, which has the property useNewUrlParser: true – it indicates to the infrastructure mongodb, that it is necessary to use a new address parcel server.

Then, a connection to the server is made using the connect method. The method accepts as a parameter the callback function which is triggered when the connection is established. This function accepts two parameters: err (an error that occurred during the connection) and client (a link to a client connected to the server).

If a connection error occurs, we can use the value err to get an error.

If there is no error, we can communicate with the server through the client object.

At the end of the database, we have to close the connection using the client.close() method.

Database, collections, and documents

Having received the object of the disabled client, we can access the database on the server. For this purpose, the method:

client.db("name_bd");

As a parameter, the name of the database we want to connect to is passed to the method.

The database in MongoDB has no tables. Instead, all data falls into collections. And within node.js, to interact with the database (add, delete, read data) we need to get the collection object. To do this, we use the db.collection method (“name_collection”), to which the name of the collection is passed.

Unlike tables in relational systems where all data is stored as rows, in MongoDB collections, data are stored as documents. For example, let us add one document to the database. For this purpose, define the following file app.js in the project directory:

const MongoClient = require("mongodb").MongoClient;

const url = "mongodb://localhost:27017/";
const mongoClient = new MongoClient(url, { useNewUrlParser: true });

mongoClient.connect(function(err, client){

const db = client.db("usersdb");
const collection = db.collection("users");
let user = {name: "Tom", age: 23};
collection.insertOne(user, function(err, result){

if(err){
return console.log(err);
}
console.log(result.ops);
client.close();
});
});

As a database, “usersdb” is used here. It does not matter that there is no such database on the MongoDB server by default. The server shall automatically create such a database the first time it is accessed.

Once connected, we shall access the “users” collection:

const collection = db.collection("users");

Again, it does not matter that such a collection does not exist by default in the usersdb bd, it will also be created the first time.

Once we receive the collection, we can use its methods. In this case, the insertOne() method is used to add a single document – the user object. This method has two parameters – the object to be added itself and the callback function, which is executed after adding. In this function, two parameters are used: err (an error that may occur during the operation) and result (the result of the operation is the added object).

In the callback function, the added object is inspected using the result.ops property. Moreover, it is no longer just a user object, but an object that is obtained back from the database and contains the identifier set at the time of adding.

Now, let us move on the hard disk to the directory where mongodb is installed, and in this directory, let us move to the folder bin:

move on the hard disk to the directory where mongodb is installed

Let’s run the mongodb server, which is located in this directory and which is a console program mongod.

Let's run the mongodb server, which is located in this directory and which is a console program mongod.

Then we run our app.js file. As we can see, apart from the initial properties here, the document has an additional property _id, which is a unique identifier of the document that is assigned by the server when it is added.

NodeJS MongoDB Tutorial

 

Enteros

About Enteros

IT organizations routinely spend days and weeks troubleshooting production database performance issues across multitudes of critical business systems. Fast and reliable resolution of database performance problems by Enteros enables businesses to generate and save millions of direct revenue, minimize waste of employees’ productivity, reduce the number of licenses, servers, and cloud resources and maximize the productivity of the application, database, and IT operations teams.

The views expressed on this blog are those of the author and do not necessarily reflect the opinions of Enteros Inc. This blog may contain links to the content of third-party sites. By providing such links, Enteros Inc. does not adopt, guarantee, approve, or endorse the information, views, or products available on such sites.

Are you interested in writing for Enteros’ Blog? Please send us a pitch!

 


RELATED POSTS

Optimizing Cloud Resource Usage and Database Performance in Media & Entertainment: A Cloud FinOps Approach with Enteros

  • 10 June 2025
  • Database Performance Management

    In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…

    Continue Reading

    Optimizing Healthcare RevOps with Enteros: Enhancing Data Lake and Database Performance for Scalable Clinical Operations

    • Database Performance Management

      In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…

      Continue Reading

      Driving Financial Clarity in Insurance: Enhancing Cost Attribution and Database Performance with Enteros Cloud FinOps

      • 9 June 2025
      • Database Performance Management

        In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…

        Continue Reading

        Enteros and Cloud FinOps in Banking: Unifying Observability, RevOps, and AIOps for Smarter Financial IT Operations

        • Database Performance Management

          In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…

          Continue Reading

          Company

          • Production Database Performance Management
          • Enteros Professional Expert Services
          • NoSQL
          • Contact Us

          Solutions

          • DevOps
          • IT Production Operations
          • CFO: Maximize Financial Efficiency with Augmented FinOps
          • Engineering Manager
          • Retail

          UpBeat SaaS

          • Performance Explorer-i – Oracle Database Performance Management
          • High Load Capture – High Precision Database Performance Management
          • DBAct
          • Grid2Go – Advanced Database Analysis
          • Load2Test for Databases

          Resources

          • Verticals
          • Case Studies
          • UpBeat Access
          • UpBeat Documentation
          • Privacy Policy
          • Terms of Service

          Connect with Us

          Copyright © 2025 | Enteros, Inc. All Rights Reserved

          🎉 Thank you for subscribing!

          You're now on the list for database FinOps strategies and performance insights.