Database

MongoDB: A Complete Guide to the NoSQL Database Revolution

MongoDB is an open-source, document-oriented NoSQL database. Unlike traditional relational databases that use tables, MongoDB stores data in flexible, JSON-like documents. This structure makes MongoDB ideal for handling unstructured or semi-structured data.

 

MongoDB: The NoSQL Database Revolutionizing Data Management

MongoDB is a leading NoSQL database that has transformed the way we manage and interact with data in modern applications. Its scalability, flexibility, and ease of use have made it a favorite among developers and businesses alike. In this blog, we'll dive into MongoDB, exploring its features, use cases, and how it differs from traditional databases.


What is MongoDB?

MongoDB is an open-source, document-oriented NoSQL database. Unlike traditional relational databases that use tables, MongoDB stores data in flexible, JSON-like documents. This structure makes MongoDB ideal for handling unstructured or semi-structured data.


Key Features of MongoDB

  1. Document-Oriented Storage
    MongoDB stores data as BSON (Binary JSON) documents. Each document is a record that contains key-value pairs, making it easy to map to objects in modern programming languages.
  2. Schema Flexibility
    MongoDB does not require a predefined schema. This flexibility allows developers to evolve their database structure over time without complex migrations.
  3. Scalability
    Built with horizontal scalability in mind, MongoDB supports sharding, enabling it to handle massive amounts of data across multiple servers.
  4. Indexing and Querying
    MongoDB provides powerful indexing options and supports complex queries, including geospatial, text search, and aggregation pipelines.
  5. High Availability
    With built-in replication and automated failover, MongoDB ensures high availability of data.
  6. Integration with Modern Tools
    MongoDB integrates seamlessly with frameworks, languages, and tools like Node.js, Python, and Kafka, making it ideal for modern tech stacks.
  7. Community and Ecosystem
    With a vast community and a rich ecosystem of tools like MongoDB Atlas (cloud service), Compass (GUI), and Realm (mobile database), MongoDB simplifies development.

MongoDB vs. Relational Databases

FeatureMongoDBRelational Databases
Data ModelDocument-oriented (JSON-like)Table-based
SchemaSchema-lessFixed schema
ScalingHorizontal (Sharding)Vertical (Scaling up hardware)
TransactionsSupports multi-document ACIDFully ACID-compliant
FlexibilityHighLimited

 

Setting Up MongoDB

Installation

  1. Download:
    Visit the  and download the appropriate version for your operating system.
  2. Install and Start:
    Follow the installation instructions for your OS. Once installed, start the MongoDB server.

    Move into the MongoDB community  edition , then click on MongoDB server( you need to  download MongoDB server) , before click on download button select appropriate version,platform and package (note for by system if choose version(current one),platform (Ubuntu 24.04 x64) and Package (server).

    once .deb file is downloaded open terminal and install/ execute it on your local machine

    cd  Downloads
    sudo dpkg -i downloaded_file.deb

    To check the either mongod service is sunning or not hits following command

    sudo systemctl status mongod.service

    If status is not active you can make it active by command

    sudo systemctl start mongod.service

    this will start mongod server or mongo daemon service which is responsible for starting mongod server.

    Then you can connect to the MongoDB  server using client like mongosh or graphical interface like mongodb compass.

     

    Setup MongoDB shell

    Let's start with downloading the mongodb shell. for that ,  in official website of mongodb , move to the Tools section then click on MongoDB shell , After that select version, package(Debian (10+) / ubuntu (18.04) x64) ) and package (deb).

    At Last you need to execute this file as 

    sudo dpkg -i downloaded_file.deb 

     Finally you can connect to mongodb server using mongodb shell

    mongosh

     

    Setup MongoDB Compass(GUI)

    For installing the mongodb compass in your system  you need to download the  MongoDB compass  .deb  with proper version (latest one) , platform (ubuntu 64-bit  (16.04+)) and package (deb) from the Tools section and execute file with the command.

    sudo dpkg -i downloaded_file.deb

    To start mongodb compass go to the App section and opened it.

    To connect to local mongodb connection click on Add connection button then you will see  url as mongodb://localhost;27017 as  by default mongodb server is running on our localhost and port is 27017.

    click on connect button to conect mongodb local server with the mongodb compass.

     

    Setup MongoDB  Atlas

    You can also create online or cloud version of mongodb  for the database management for that you need to create an account by visiting  https://account.mongodb.com/account/login

    After successfully login into the mongodb Atlas , create a new project  with proper name and then it will redirect to  newly created project  with the option of creating cluster , click on create cluster button then , Fill form by selecting  M0 Free package ( for free usages) , entering cluster name, region,provider and click on  create Deploymnet button 

    it will create a new cluster or mongodb cloud  server for you with provide username  and password as well copy them (as it will needed to connect with the cloud mongodb server)

    After All click on Create Database user button to ceate user on database with the provided username and password.

    Finally Click on Choose Connecion Button, then go through Drivers  to get connect to your application (like project on fastapi,flask, mongodb compass so on) with mongodb driver.

    You need to select driver like python, nodejs according to the requirements. 

    Then you can see the code to connect mongodb driver with the application  in view full code sample section

    # python -m pip install "pymongo[srv]"
    
    from pymongo.mongo_client import MongoClient
    from pymongo.server_api import ServerApi
    
    uri = "mongodb+srv://user_name:[email protected]/?retryWrites=true&w=majority&appName=cluster_name"
    
    # Create a new client and connect to the server
    client = MongoClient(uri, server_api=ServerApi('1'))
    
    # Send a ping to confirm a successful connection
    try:
        client.admin.command('ping')
        print("Pinged your deployment. You successfully connected to MongoDB!")
    except Exception as e:
        print(e)
     

    Then you can connect this cloud server with the mongodb shell by establishing new connection using the uri

    mongodb+srv://user_name:[email protected]/?retryWrites=true&w=majority&appName=cluster_name

     

MongoDB (where mongo means huge) , it is the data server where we create or manage many database.

  • documents are store in Bson format  ( Bson is a binary structure encoder type  information , which allows it to be traversed mush more quickly compare to json)

Some important commands in mongodb:

show dbs;
use testing_db; # switch to testing_db and if not db exit it will create database and switch into it
show collections;

CRUD Operation In MongoDB 

 Create

db.student.insertOne({"name":"ram thapa","age":1})

# response
{
  acknowledged: true,
  insertedId: ObjectId('674163171c73228eb1c1c18c')
}

Read

testing_db> db.student.find()
# response
[
  {
    _id: ObjectId('674163171c73228eb1c1c18c'),
    name: 'ram thapa',
    age: 1
  }
]

db.student.find({"name":"ram thapa"})
#response
[
  {
    _id: ObjectId('674163171c73228eb1c1c18c'),
    name: 'ram thapa',
    age: 1
  }
]

Update

db.student.update({"name":"ram thapa"},{$set:{"age":2}})
# response
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Delete

 

 

Some important commands for mongo-db 

1.{ "name": "amrit" }
2.{ "age": { "$gt": 25 } }    { "age": { "$lt": 30 } }   { "age": { "$gte": 20, "$lte": 30 } }   (inclusive)
3.{ "$or": [ { "name": "amrit" }, { "age": 25 } ] }
4.{ "$and": [ { "name": "amrit" }, { "age": 25 } ] }
5.{ "name": { "$regex": "^am", "$options": "i" } }   // start with am
6.{ "name": { "$regex": "rit", "$options": "i" } }  // Contains "rit":
7.{ "address.city": "Kathmandu" }
8.{ "skills": { "$all": ["Python", "MongoDB"] } }  //Check if both values exist:
9.{ "status": { "$ne": "inactive" } }  // not equal
10.{ "email": { "$ne": null } }  // not equal to null
11.{ "name": /amrit/ }   { "name": /amrit/i } (case insensitive)  { "name": /^amrit/ } ( Starts with a value)
{ "name": /amrit$/ } (ends with value)
12.{ "name": { "$not": /amrit/ } }  (doesnot match pattern)
13.{ "$or": [ { "name": /amrit/ }, { "name": /john/ } ] }  //Contains any one of multiple patterns
14.{ "name": /\bamrit\b/ }  (Contains exact word)
15.{ "name": /^[A-Z]/ }  (start with capital letter)   { "name": /^[a-z]/ }  (start with lowerletter)
16.{ "name": /\d$/ }  (ends with digits)
17.{ "name": /^a.*t$/i }  (Starts with A and ends with T (case-insensitive)
18.{ "name": /^[A-Za-z]+$/ } (Only letters (no digits/symbols))
19.
20.
{ "phone": /^\d+$/ }  (Only digits (e.g., for phone or ID field))
{ "email": /^[\w.-]+@[a-zA-Z_-]+?\.[a-zA-Z]{2,3}$/ } (Email format match (simple))
{ "description": /mongodb|flask|python/i }  (Match either “mongodb”, “flask”, or “python” in description:)
{ "name": { "$not": /amrit/i } }  (doesnot contain word)
{ "name": /^.{3,}$/ }  (Field with at least 3 characters)

About author

author image

Amrit panta

Fullstack developer, content creator



Scroll to Top