MongoDB

Amila Devin
8 min readMar 17, 2022
MongoDB

What is the MongoDB?

  • MongoDB is written in C++.
  • It is intuitive and easy to use NoSQL Database.
  • Available as community and enterprise edition.
  • However, the community edition itself is very powerful.
  • 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. Multiple databases are commonly found on a single MongoDB server.

Collection

The term “collection” refers to a group of MongoDB documents. It’s the same thing as an RDBMS table. Within a single database, there is a collection. A schema is not enforced by collections. Distinct fields can be found in different documents within a collection. In most cases, all the documents in a collection serve the same or comparable purposes.

Document

A document consists of a collection of key-value pairs. The schema of documents is dynamic. Documents in the same collection don’t have to have the same set of fields or structure, and common fields in a collection’s documents might contain various types of data.

The following table shows the relationship of RDBMS terminology with MongoDB.

relationship of RDBMS terminology with MongoDB
Relationship of RDBMS terminology with MongoDB

Sample Document

The document structure of a blog site is simply a comma separated key value pair, as seen in the following example.

{
_id: ObjectId(7df78vd8fe2e)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'Amila Devin',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2022,3,16,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2022,3,16,7,45),
like: 5
}
]
}

_id is a 12-byte hexadecimal integer that ensures each document’s uniqueness. When inserting the document, you can specify _id. If you don’t give an id for each document, MongoDB will generate one for you. These 12 bytes have four bytes for the current timestamp, three bytes for machine id, two bytes for MongoDB server process id, and three bytes for basic incremental VALUE.

  • A typical schema design for a relational database displays the number of tables and the relationships between them. While in MongoDB, there is no concept of relationship.

Advantages of MongoDB over RDBMS

  • Schema less - MongoDB is a document database that stores several documents in a single collection. The number of fields, content, and size of a document might vary from one to the next.
  • Structure of a single object is clear.
  • No complex joins.
  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL.
  • Tuning.
  • Ease of scale-out − MongoDB is easy to scale.
  • Conversion/mapping of application objects to database objects not needed.
  • Uses internal memory for storing the (windowed) working set, enabling faster access of data.

Why Use MongoDB?

  • Document Oriented Storage − Data is stored in the form of JSON style documents.
  • Index on any attribute
  • Replication and high availability
  • Auto Sharding
  • Rich queries
  • Fast in-place updates
  • Professional support by MongoDB

Where to Use MongoDB?

  • Big Data
  • Content Management and Delivery
  • Mobile and Social Infrastructure
  • User Data Management
  • Data Hub
Install MongoDB Community on Windows using msiexec.exe — Steps
Install MongoDB Community on Windows using msiexec.exe — Steps

Read More >>

  • After the installation, Add the installation path ( C:\Program Files\MongoDB\Server\5.0\bin ) to the system Environment.

—for that, go to the windows search bar and type env and open Edit the system environment variables.

env

— After that click on the Environment Variables..

— Then Select the path and click on edit button

— Then Click on New button and Past the path ( C:\Program Files\MongoDB\Server\5.0\bin ) into the new row and click ok.

  • After that You can start the mongoDB server

— To do that open the Windows Powershell and type mongo.

— Then you can create, delete databases and insert,update,delete data using commands.

MongoDB Cheats

show all Databases

show dbs

Show Current Database

db

Create or Switch Database

use acme

Drop

db.dropDatabase()

Create Collection

db.createCollection('posts')

Show Collections

show collections

Insert Row

db.posts.insert({
title: 'Post One',
body: 'Body of post one',
category: 'News',
tags: ['news', 'events'],
user: {
name: 'John Doe',
status: 'author'
},
date: Date()
})

Insert Multiple Rows

db.posts.insertMany([
{
title: 'Post Two',
body: 'Body of post two',
category: 'Technology',
date: Date()
},
{
title: 'Post Three',
body: 'Body of post three',
category: 'News',
date: Date()
},
{
title: 'Post Four',
body: 'Body of post three',
category: 'Entertainment',
date: Date()
}
])

Get All Rows

db.posts.find()

Get All Rows Formatted

db.posts.find().pretty()

Find Rows

db.posts.find({ category: 'News' })

Sort Rows

# asc
db.posts.find().sort({ title: 1 }).pretty()
# desc
db.posts.find().sort({ title: -1 }).pretty()

Count Rows

db.posts.find().count()
db.posts.find({ category: 'news' }).count()

Limit Rows

db.posts.find().limit(2).pretty()

Chaining

db.posts.find().limit(2).sort({ title: 1 }).pretty()

Foreach

db.posts.find().forEach(function(doc) {
print("Blog Post: " + doc.title)
})

Find One Row

db.posts.findOne({ category: 'News' })

Find Specific Fields

db.posts.find({ title: 'Post One' }, {
title: 1,
author: 1
})

Update Row

db.posts.update({ title: 'Post Two' },
{
title: 'Post Two',
body: 'New body for post 2',
date: Date()
},
{
upsert: true
})

Update Specific Field

db.posts.update({ title: 'Post Two' },
{
$set: {
body: 'Body for post 2',
category: 'Technology'
}
})

Increment Field ($inc)

db.posts.update({ title: 'Post Two' },
{
$inc: {
likes: 5
}
})

Rename Field

db.posts.update({ title: 'Post Two' },
{
$rename: {
likes: 'views'
}
})

Delete Row

db.posts.remove({ title: 'Post Four' })

Sub-Documents

db.posts.update({ title: 'Post One' },
{
$set: {
comments: [
{
body: 'Comment One',
user: 'Mary Williams',
date: Date()
},
{
body: 'Comment Two',
user: 'Harry White',
date: Date()
}
]
}
})

Find By Element in Array ($elemMatch)

db.posts.find({
comments: {
$elemMatch: {
user: 'Mary Williams'
}
}
}
)

Add Index

db.posts.createIndex({ title: 'text' })

Text Search

db.posts.find({
$text: {
$search: "\"Post O\""
}
})

Greater & Less Than

db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })

Play around with MongoDB using Docker

Play around with MongoDB using Docker
Play around with MongoDB using Docker
  • First of all we need to install Docker
  • After the Doker installation, have to download the mongo image

— To do that open your git bash and execute the following command

docker pull mongo:latest

installing mongo image

— To check the images execute the following command.

docker images

Get all images in docker
  • Then, to run the mongo image execute the following command in the terminal (also you can make a directry and do above)

docker run -d -p 27017:27017 -v ~/Docker-MongoDB:/data/db — name mymongo mongo:latest

Run the mongo image
  • Then we can go inside to the created container.

— To do that execute the following command .

docker exec -it mymongo bash

— If you get “the input device is not a TTY. If you are using mintty, try prefixing the command with ‘winpty’ ” error you can execute the following code

winpty docker exec -it mymongo bash

go inside to the created container.
  • After that you can run the MongoDB Server using mongo Command and can run all the command what we talk about previously 😍.
Run MongoDB Server using docker

MongoDB Atlas

MongoDB Atlas

MongoDB Atlas makes it easy to set up, operate, and scale your MongoDB deployments in the cloud. From high availability to scalability, security to disaster recovery — we've got you covered.

MongoDB Atlas is

  • Automated
  • Flexible
  • Secure
  • Scalable
  • Highly available
  • High performance

Get Started

--

--

Amila Devin

BSc (Hons) in Information Technology Specialising in Software Engineering undergraduate at SLIIT