Introduction to MongoDB along with differences between SQL and No-SQL
Introduction
MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.
Database
Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.
It stores data in BSON format.
Differences between SQL and NoSQL
Topics | SQL | NoSQL |
---|---|---|
Full form | Structured Query Language | Not only SQL / Non-SQL / non-relational |
Schema | SQL databases must have predefined schema | NoSQL databases are schema less |
Type | Store data in table based fromat | Storage of data is in key value pairs |
General Use Case | Used for ACID compliant tasks | Used for fast availability of data |
Scalability | Vertical | Horizontal |
Excels at | Multi-row transaction | unstructured data storage |
Consistency | Strong consistency | Eventual Consistency |
Designed For | OLAP | OLTP |
example | Oracle, Postgres, and MySQL | MongoDB, Redis, DynamoDB, Hbase, Casandra |
Installing and setting up MongoDB
MongoDB is a cross platform document-oriented database. Classified as a NoSQL database program, MongoDB uses JSON-like documents. The database puts the BSON data format, and puts data in collections which are present inside databases. The collections are defined by using schema. The MongoDB database is created and maintained by [MongoDB Inc.](https://en.wikipedia.org/wiki/MongoDB_Inc.)
Setup
- Add public key which contain packages for installing MongoDB:
$ sudo apt install gnupg
$ wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc>](<https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
- Create list file for MongoDB:
$ echo "deb [ arch=amd64,arm64 ] <https://repo.mongodb.org/apt/ubuntu> focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
- Reload local packages:
$ sudo apt update
- Installing MongoDB latest (stable version):
$ sudo apt-get install -y mongodb-org
For troubleshooting problems, see the MongoDB troubleshooting guide.
- running MongoDB community edition:
$ sudo systemctl start mongod
## verify if the MongoDB has started successfully
$ sudo systemctl status mongod
## want to start MongoDB on system reboot
$ sudo systemctl enable mongod
- Stopping and restarting MongoDB:
## stop
$ sudo systemctl stop mongod
## restart
$ sudo systemctl restart mongod
- Using MongoDB:
## connect to the MongoDB using mongosh *connects to the default port 27017.
$ mongosh
If every thing went hiccup free then you are connected to the local MongoDB on default port 27017.
MongoDB Compass GUI for MongoDB
1. Download compass by going to the following link: MongoDB Compass
2. Install the deb package.
3. After installation open the compass application
Now open your terminal and type mongosh
Not put the above obtained Connecting to
link in the MongoDB Compass.
There you have it you are successfully connected to the MongoDB through compass application. Now you can interact with your MongoDB database through graphical user interface.
CRUD operation in mongosh
Open terminal and type mongosh
which connects you to the MongoDB
$ mongosh
Interface like the bellow image will apear.
Creating Database and collection
## creating Database
use test;
## Creating collection
db.createCollection("users");
INSERT
db.users.insert({
name: "Shuvam", email: "hello@hello.com", phone: 7878787878
});
SELECT
db.users.find().pretty();
UPDATE
db.users.update({ name: "Shuvam" }, { name: "Shuvam Lamichhane" });
DELETE
db.users.remove({ email: "hello@hello.com" }, { justOne: true });
Using MongoDB along with node (mongodb package)
initialize a node application and follow along
# initiliazing a node application
$ mkdir mongodb-package-crud && mongodb-package-crud
## creating files
$ touch index.js .env
## initializing the application
$ npm init -y
## open it in your favorite code editor
$ code .
Install the package
$ npm i mongodb dotenv
Initializing the DB
The following code is present in file: index.js
const { MongoClient } = require('mongodb');
require("dotenv").config();
// Connection URL
const url = process.env.MONGO_URL;
const client = new MongoClient(url);
// Database Name
const dbName = "scanskill";
async function main() {
//* Connecting to the database
await client.connect();
console.log("Connected successfully to MongoDB...");
const db = client.db(dbName);
const collection = db.collection("user");
//* insert operation
await insertUser(collection);
//* Select operation
await selectUser(collection);
//* Update operation
await updateUser(collection);
//* Delete operation
await deleteUser(collection);
//* closing connection to the mongodb
console.log("Closing connection with MongoDB...")
await client.close();
}
try {
main();
} catch (error) {
console.log(error);
}
CRUD Operations
INSERT
async function insertUser(collection) {
const insertResult = await collection.insertMany([
{ name: "Ramesh", rollNo: 1 },
{ name: "Suresh", rollNo: 2 },
{ name: "Kamlesh", rollNo: 3 },
]);
console.log("Inserted User =>", insertResult);
}
SELECT
async function selectUser(collection) {
const findResult = await collection.find({}).toArray();
console.log("Found Users =>", findResult);
}
UPDATE
async function updateUser(collection) {
const updateResult = await collection.updateOne(
{ rollNo: 3 },
{ $set: { name: "Josh" } }
);
console.log("Updated User =>", updateResult);
}
DELETE
async function deleteUser(collection) {
const deleteResult = await collection.deleteMany({ rollNo: 1 });
console.log("Deleted Users =>", deleteResult);
}
Using Object Data Modeling (ODM) Library Mongoose to interact with MongoDB
Creating the Project
## Creating and going into the file
$ mkdir MongoNode && cd MongoNode
## creating a node project
$ npm init -y
## creating a index.js file
$ touch index.js
## installing needed dependencies
$ npm i mongoose
## opening with your favourie code editor
$ code .
We use Mongoose as it is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. We use mongoose instead of mongodb which is the official driver for MongoDB.
Coding
Connection to the Database
const mongoose = require("mongoose");
//* this url can be recieved by mongosh connecting to: ${string} trough the terminal
const mongodbUrl = `mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.3`;
//* connecting to the mongodb database
function dbConnect() {
mongoose.connect(mongodbUrl, (err) => {
if (!err) {
console.log("Connected to the Mongo Database.");
} else {
console.log(
`[${err}, Connection with the MongoDB could not be established.]`
);
}
});
}
dbConnect();
Creating schema of collection
//* creating a collection
const schema = new mongoose.Schema(
{
_id: mongoose.Schema.Types.ObjectId,
name: {
type: String,
},
email: {
required: true,
type: String,
},
password: {
required: true,
type: String,
},
},
{ versionKey: false },
{ strict: false }
);
const User = mongoose.model("User", schema);
In the above schema the collection User is being made. The user has keys _id which is default uuid, name which is a String, email is string and is required, it’s the same with the password.
Inserting data in the Database (CREATE)
//* Inserting a data to the database
function insertNewUser() {
const newUser = {
_id: new mongoose.Types.ObjectId,
name: "Hello World!",
email: "hello@scanskill.com",
password: "veryStrongP@ssword123"
};
const user = new User(newUser);
//* Saves the data to the database
const dataSaved = user.save();
if(dataSaved) {
console.log(newUser);
}
};
insertNewUser();
Looking data from the compass:
Getting data from the Database (READ)
//* Fetching all data from the database
function getAllUsers() {
User.find((err, result) => {
if(!err) {
console.log(result);
}
});
}
getAllUsers();
Updating data present inside the Database (UPDATE)
//* updating user form the database
function updateUser() {
User.updateOne(
{ email: "hello@scanskill.com" },
{ name: "ScanSkill", password: "weakPassword" },
( err, result ) => {
if(!err) {
console.log(result);
}
}
);
}
updateUser();
Deleting data present inside the Database (DELETE)
//* removing user form the database
function removeUser() {
User.deleteOne(
{ email: "hello@scanskill.com", name: "ScanSkill" }
( err, result ) => {
if(!err) {
console.log(result);
}
}
);
}
removeUser();
Conclusion
In this chapter, we’ve saw a overview to MongoDB database, difference between SQL and No-SQL database, and how it works with examples in mongosh
, node
, and using packages like: mongodb
and mongoose
.