Skip to content

lovnishverma/mongodb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

12 Commits
ย 
ย 
ย 
ย 

MongoDB Installation and Basic CRUD Operations

image

What is MongoDB?

MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Itโ€™s schema-less, meaning the structure of the data can evolve over time.

image


Letโ€™s see how RDBMS and MongoDB differ:

image

Key Features:

  • ๐Ÿ“„ Document-oriented (stores data in JSON-like documents).
  • ๐Ÿ“Š High scalability and performance.
  • ๐Ÿ—„๏ธ Schema-less, meaning flexible data structures.
  • ๐Ÿ”„ High availability through replication.
  • ๐Ÿ› ๏ธ Supports complex queries with the Aggregation Framework.

Installation Steps

Step 1: Download MongoDB

  1. Visit the MongoDB Download Center.
  2. Select your operating system (Windows, macOS, or Linux) and download the appropriate version.

Step 2: Install MongoDB

  • For Windows:
    • Run the .msi file and complete the setup.
    • Add the MongoDB bin folder to your system PATH for easy access.
  • For macOS (Homebrew):
    brew tap mongodb/brew
    brew install mongodb-community
  • For Linux: Use your package manager, e.g., apt for Ubuntu:
    sudo apt update
    sudo apt install -y mongodb

Step 3: Start MongoDB

  1. Start the MongoDB server:

    mongod --dbpath <path_to_data_directory>

    Replace <path_to_data_directory> with the path where you want to store data.

  2. Connect to the MongoDB shell:

    mongo

Basic CRUD Operations in MongoDB

CRUD stands for Create, Read, Update, and Delete. Letโ€™s use a collection named students .

image

1. Create (Insert)

Use the insertOne() or insertMany() methods to add data.

// Insert one document
use school;
db.students.insertOne({ name: "Rajesh Kumar", age: 20, city: "Delhi" });

// Insert multiple documents
db.students.insertMany([
  { name: "Priya Sharma", age: 19, city: "Mumbai" },
  { name: "Amit Singh", age: 22, city: "Bangalore" }
]);

2. Read (Find)

Query data using the find() or findOne() methods.

// Find all documents
db.students.find();

// Find documents with a specific condition
db.students.find({ city: "Mumbai" });

// Find documents with age greater than 20
db.students.find({ age: { $gt: 20 } });

// Find one document
db.students.findOne({ name: "Priya Sharma" });

3. Update

Use updateOne(), updateMany(), or replaceOne() to modify data.

// Update one document
db.students.updateOne(
  { name: "Rajesh Kumar" },
  { $set: { age: 21 } }
);

// Update multiple documents
db.students.updateMany(
  { city: "Mumbai" },
  { $set: { status: "Active" } }
);

// Replace a document
db.students.replaceOne(
  { name: "Amit Singh" },
  { name: "Amit Singh", age: 23, city: "Hyderabad" }
);

4. Delete

Use deleteOne() or deleteMany() to remove data.

// Delete one document
db.students.deleteOne({ name: "Priya Sharma" });

// Delete multiple documents
db.students.deleteMany({ city: "Mumbai" });

Aggregation Framework

Aggregation allows processing and analyzing data. Letโ€™s explore with examples:

Example 1: Grouping

Count the number of students by city:

db.students.aggregate([
  { $group: { _id: "$city", count: { $sum: 1 } } }
]);

Example 2: Average Age

Calculate the average age of students:

db.students.aggregate([
  { $group: { _id: null, avgAge: { $avg: "$age" } } }
]);

Example 3: Sorting

Sort students by age in descending order:

db.students.aggregate([
  { $sort: { age: -1 } }
]);

To sort students by age in ascending order, use the $sort stage in the aggregation pipeline with age: 1 (where 1 indicates ascending order):

db.students.aggregate([
  { $sort: { age: 1 } }
]);

This will return the list of students sorted from the youngest to the oldest. If you are not using aggregation, you can achieve the same with a simple find() and sort():

db.students.find().sort({ age: 1 });

Both methods will work, so you can choose based on your needs! ๐Ÿ˜Š

Useful Commands

List all databases:

show dbs;

Switch to (or create) a database:

use school;

List all collections in a database:

show collections;

Drop a collection:

db.students.drop();

Summary

MongoDBโ€™s flexibility and simplicity make it a great choice for beginners and professionals alike. Start by mastering basic CRUD operations, then explore the powerful Aggregation Framework for advanced queries.๐Ÿ˜Š

References:

https://www.infoq.com/articles/Starting-With-MongoDB/

https://www.w3schools.com/mongodb/

https://www.geeksforgeeks.org/mongodb-tutorial/

https://www.mongodb.com/resources/products/fundamentals/basics

https://www.tutorialspoint.com/mongodb/index.htm

https://www.youtube.com/watch?v=c2M-rlkkT5o

About

MongoDB Installation and Basic CRUD operations

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

  •  

Packages

No packages published