MongoDB is No-SQL or no-structure Database which stores data in key-value pair. Unlike JSON, MongoDB stores data in BSON format which stands for Binary JSON. MongoDB is a popular document-oriented database program designed to be highly scalable and flexible. It is a NoSQL database, meaning it does not use the traditional relational database model. Instead, it stores data in a flexible schema-less format, which allows for easy scalability and flexibility. MongoDB is widely used in modern web applications, where it is used to store large amounts of data in a fast and efficient manner.
MongoDB's Key Features
π Schema Flexibility: MongoDB is schema-less! No rigid structures, embrace changes easily!
π Document-Oriented: Data stored in JSON-like documents, perfect for complex data ποΈ.
β No Joins: Forget complex joins! Denormalize & embed data within documents for speed π.
π Horizontal Scalability: Shard data across servers, handle big apps with ease.
β« High Availability: Replication with replica sets, no downtime! π
πΊοΈ Geospatial Indexing: Powerful support for location-based info π.
π Dynamic Queries: Ad-hoc queries with ease, no strict schema π΅οΈ.
π Integrated Caching: Memory Mapped Files for faster reads π.
π ACID Transactions: Ensure data consistency and integrity across operations π‘οΈ.
π JSON-BSON Format: Efficiently store and manipulate data with BSON π¦.
Choose MongoDB for flexible, scalable, and high-performance applications! ππ
Mongo Db Node JS/Express Js Setup
Setting up MongoDB, Node.js, and Express.js involves several steps. We can either use MongoDB Atlas which is remote MongoDB's remote DB service or we can use MongoDB Compass where we need to set up everything locally. I will show the MongoDB Compass setup.
MongoDB Compass π§
π§ MongoDB Compass is a graphical user interface (GUI) for MongoDB, which helps you navigate and explore your MongoDB databases with ease. It provides a compass-like interface to visualize and interact with your data, making database management a breeze. π
Install MongoDB Download and install MongoDB from the official website: https://www.mongodb.com/try/download/community
Install Node.js and npm Download and install Node.js: nodejs.org
Create a new project folder Navigate into it using the terminal/command prompt.
Initialize a new Node.js project
Run the following command in your project folder to create a package.json file:
npm init -y
To create Schemas you can Mongoose package.
A detailed explanation is shown below.
Install Express.js and other dependencies
Install Express.js and Mongoose(MongoDB library):
npm install express mongoose
Set up the server with Express.js
Create a new file named
app.js
orindex.js
in your project folder.Add the following code to set up a basic Express.js server:
Sure! Here's a basic setup for an Express.js server in a file named
app.js
:const express = require('express'); const mongoose = require("mongoose"); const app = express(); app.use(express.json()); const port = 8000; /* NOTE:Department is the Database name you can choose any name you like. If the Db doesn't exist then it will automatically create a new one. */ //Db connection const DbConnection = async()=>{ try{ await mongoose.connect("mongodb://localhost:27017/Department") console.log("Db Connected..."); }catch(error){ console.log("Db Connection Failed...") } } app.get('/', (req, res) => { res.send('Hello, world!'); }); app.listen(port, () => { DbConnection(); console.log(`Server started on http://localhost:${port}`); });
You can run this server by executing the following command in your project folder:
node app.js
After running the server, you should see the message "Server started on http://localhost:8000" in the console. You can access the server by visiting "http://localhost:8000" in your web browser or making a GET request to that URL using tools like Postman or cURL.
Mongo Db CRUD ππβοΈβ
To Work with CRUD functionalities using express we need to define a schema first.
const EmployeeSchema = new mongoose.Schema({
name: { type: String, reqired: true },
salary: { type: Number, required: true },
age: Number,
date: { type: Date, default: Date.now },
});
// craeting model //collection creation
const EmployeeModel = new mongoose.model("Employee", EmployeeSchema);
π Create :
For the Creation of Documents, we can either insert one by one or multiple at a time. Let's see one by one or insert one first.
const createDocument = async () => {
try {
const employee={
name: "Akash",
salary: 50000,
age: 24,
};
const data = await EmployeeModel.create(employee);
console.log(data);
} catch (error) {
console.log(error);
}
};
createDocument();
Insert Multiple
const insertManyDocuments = async () => {
try {
const employees = [
{ name: "John", salary: 50000, age: 30 },
{ name: "Jane", salary: 60000, age: 28 },
{ name: "Bob", salary: 55000, age: 35 },
];
const data = await EmployeeModel.insertMany(employees);
console.log(data);
} catch (error) {
console.log(error);
}
};
// Call the function to insert multiple documents
insertManyDocuments();
π Read (R): Retrieving data from MongoDB.
// It will show all the Documents
const findAll = async () => {
try {
const data = await EmployeeModel.find();
console.log(data);
} catch (error) {
console.log(error);
}
};
// It will show Documents with name:"Akash"
const findWithName = async () => {
try {
const name="Akash";
const data = await EmployeeModel.find(name);
console.log(data);
} catch (error) {
console.log(error);
}
};
// It will show Documents with salary<60000
const findWithSalary = async () => {
try {
const salary=60000;
const data = await EmployeeModel.find({ salary: { $lt: salary } });
console.log(data);
} catch (error) {
console.log(error);
}
};
βοΈ Update (U): Modifying data in MongoDB.
//upadating name using _id
const updateData = async (_id) => {
try {
//will return acknoledgment only
// const updatedData = await EmployeeModel.updateOne({ _id }, { $set: { name: "Voldermort" } });
//will return the old value
// const updatedData = await EmployeeModel.findByIdAndUpdate(
// { _id },
// { $set: { name: "Lord Voldermort" } }
// );
//will return new updated value
const updatedData = await EmployeeModel.findByIdAndUpdate(
{ _id },
{ $set: { name: "Tom Riddle" } },
{ new: true }
);
console.log(updatedData);
} catch (error) {
console.log(error);
}
};
// Call the function to update a document by id
updateData("64be568dfdbb44bb0f7e3fds4");
β Delete (D): Removing data from MongoDB.
const deleteDocumentById = async (id) => {
try {
// Use the findByIdAndDelete method
const deletedEmployee = await EmployeeModel.findByIdAndDelete(id);
if (!deletedEmployee) {
console.log("Employee not found!");
} else {
console.log("Employee deleted:", deletedEmployee);
}
} catch (error) {
console.log(error);
}
};
// Call the function to delete a document by id
const documentIdToDelete = "603e846059786a2fd8c93d18";
deleteDocumentById(documentIdToDelete);
Conclusion
n conclusion, MongoDB emerges as a powerful NoSQL database that offers a flexible and scalable solution for modern applications. Its document-oriented data model, schema flexibility, and support for unstructured and semi-structured data make it an ideal choice for projects with dynamic and evolving data requirements. Throughout this article, we explored the key features that differentiate MongoDB from traditional relational databases, highlighting its ability to handle diverse data types, horizontal scalability, and high availability through replica sets. We also delved into essential CRUD operations using MongoDB with Express.js and Mongoose, showcasing how to create, read, update, and delete data seamlessly.