In this article, you’ll learn how to install NodeJs, MongoDB on Ubuntu 18.04

Node.js is a platform built on Chrome’s JavaScript runtime for scalable network applications and easily building and fast building applications.

The latest version node js PPA is maintaining by its official website and we can add this PPA to your Ubuntu systems and install node js on ubuntu with easy commands.

Node js package is available in the current release and LTS release. So, It is your choice to select which version you want to install on the system as per your requirements.

To install Nodejs on Ubuntu, let’s add the PPA to your system.

$ sudo apt-get install curl python-software-properties

$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash –

Now you successfully added node js PPA in your Ubuntu system.

Now execute the below command to install Node on and Ubuntu using apt-get.

This will also install NPM with Node.js.

This command also installs many other dependent packages on your Ubuntu system.

$ sudo apt-get install nodejs

After installation please verify your versions by following commands.

$ node -v

v12.1.0

And also check npm version

$ npm -v

v6.9.0

Now you successfully installed node js in your machine. Now you can test your node.js by creating Hello World text.

Create a file with servertext.js and write the following code in it.

var http = require(‘http’);

http.createServer(function (req, res) {

 res.writeHead(200, {‘Content-Type’: ‘text/plain’});

 res.end(‘Hello World\n’);

}).listen(4000, “127.0.0.1”);

console.log(‘Server running at ‘)

Install MongoDB on Ubuntu

MongoDB is a NoSQL database that offers high performance, high availability and automatic scaling of the enterprise level database.

MongoDB is a NoSQL database, so you cannot use SQL to retrieve and insert data, and it does not store data in tables like MySQL.

The data is stored in a “document” structure in JSON format (called BSON in MongoDB). MongoDB introduced in 2009 and is currently being developed by MongoDB Inc.

MongoDB only offers packages for 64-bit LTS Ubuntu versions. For example 16.04 LTS (xenial), 14.04 LTS (trusty), 18.04 LTS (bionic) and so on.

Now, I will install MongoDB 4.0 on Ubuntu 18.04 LTS.

GPG keys of the software are required for the Ubuntu package manager apt (Advanced Package Tool) to ensure the authenticity and consistency of the package.

Execute the following command to import MongoDB keys to your server.

$ sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv 68818C72E52529D4

Create a source list for MongoDB by the following command.

$ sudo echo “deb http://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list

Now update the repository with the following apt command

 $ sudo apt-get update

Install MongoDB in Ubuntu using the following command

$ sudo apt-get install -y mongodb-org

Now start MongoDB and add it as a service and it started when the system is boot.

$ sudo systemctl start mongodb

$ sudo systemctl enable mongodb

$ sudo systemctl stop mongodb

Now check your MongoDB version using the following command

$ mongod –version

Node and MongoDB getting started:

Install the npm MongoDB package using the following command.

$ sudo npm install mongodb

const mongo = require(“mongodb”);

How to create a database?

To create a database in MongoDB, we can use MongoClient object and then specify the connection URL with IP address along with the database name as follows.

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://127.0.0.1:27017/testdb”;

 
MongoCli.connect(url, (err, db) => {
 if (err) throw err;
 console.log(“Database created!”);
 db.close();
 });

How to create a collection?

use createCollection() to create collection.

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://127.0.0.1:27017/”;

 
MongoCli.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 dbo.createCollection(“users”, (err, res) => {
  if (err) throw err;
  console.log(“Collection created!”);
  db.close();
 });
 });

How to Insert record?

Insert a document into users collection. We can insert a record using **insertOne()**method.

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://localhost:27017/”;

MongoCli.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 var myobj = { name: “Stringify Inc”, address: “Road No 37” };
 dbo.collection(“users”).insertOne(myobj, (err, res) => {
  if (err) throw err;
  console.log(“1 document inserted”);
  db.close()
 });
 });

How to do an update?

We can update a record or document by using the updateOne() method.

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://127.0.0.1:27017/”;

MongoCli.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 var myquery = { address: “Road No 37” };
 var newvalues = { $set: {name: “Mickey”, address: “Canyon 123” } };
 dbo.collection(“users”).updateOne(myquery, newvalues, (err, res) => {
  if (err) throw err;
  console.log(“1 document updated”);
  db.close();
 });
 })

How to do delete?

We can delete a record or document by using deleteOne() method.

const MongoClient = require(‘mongodb’).MongoClient;
const url = “mongodb://localhost:27017/”;

MongoClient.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 var myquery = { address: ‘Mountain 21’ };
 dbo.collection(“users”).deleteOne(myquery, (err, obj) => {
  if (err) throw err;
  console.log(“1 document deleted”);
  db.close();
 });
 });

How to do sort?

We can use sort() method to sort the result in ascending order or descending order. It will take one parameter and an object decide the sorting order.

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://localhost:27017/”;

MongoClient.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 var mysort = { name: 1 };
 dbo.collection(“users”).find().sort(mysort).toArray((err, result) => {
  if (err) throw err;
  console.log(result);
  db.close();
 });
 });

Below the code for descending order.

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://localhost:27017/”;

MongoCli.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 var mysort = { name: -1 };
 dbo.collection(“users”).find().sort(mysort).toArray((err, result) => {
  if (err) throw err;
  console.log(result);
  db.close();
 });
 });

How to do Limit?

We can do limit with** limit() **method.

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://localhost:27017/”;

MongoCli.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 dbo.collection(“users”).find().limit(5).toArray((err, result) => {
  if (err) throw err;
  console.log(result);
  db.close();
 });
 });

How to do Join?

MongoDB is not like a relational database, but we can do left outer join by using $lookup stage.

Let’s assume we have “orders” and “products” collections

const MongoCli = require(‘mongodb’).MongoClient;
const url = “mongodb://127.0.0.1:27017/”;

MongoClient.connect(url, (err, db) => {
 if (err) throw err;
 var dbo = db.db(“testdb”);
 dbo.collection(‘orders’).aggregate([
  { $lookup:
   {
    from: ‘products’,
    localField: ‘product_id’,
    foreignField: ‘_id’,
    as: ‘orderdetails’
   }
  }
  ]).toArray((err, res) => {
  if (err) throw err;
  console.log(JSON.stringify(res));
  db.close();
 });
 });

#node-js #mongodb #ubuntu

How to install NodeJs, MongoDB on Ubuntu 18.04
3 Likes70.90 GEEK