0% found this document useful (0 votes)
4 views14 pages

MongoDB is a No SQL database python

MongoDB is an open-source, document-oriented NoSQL database developed by 10gen, now known as MongoDB Inc., designed for high performance, scalability, and high availability. It allows for flexible data storage in the form of documents and supports various features such as ad hoc queries, indexing, and replication. Initially released in 2009, MongoDB has evolved to meet the demands of modern applications requiring efficient handling of big data.

Uploaded by

Meera Desai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views14 pages

MongoDB is a No SQL database python

MongoDB is an open-source, document-oriented NoSQL database developed by 10gen, now known as MongoDB Inc., designed for high performance, scalability, and high availability. It allows for flexible data storage in the form of documents and supports various features such as ad hoc queries, indexing, and replication. Initially released in 2009, MongoDB has evolved to meet the demands of modern applications requiring efficient handling of big data.

Uploaded by

Meera Desai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

MongoDB is a No SQL database.

It is an open-source, cross-platform,
document-oriented database written in C++.

What is MongoDB
MongoDB is an open-source document database that provides high
performance, high availability, and automatic scaling.

In simple words, you can say that - Mongo DB is a document-oriented


database. It is an open source product, developed and supported by a
company named 10gen.

MongoDB is available under General Public license for free, and it is also
available under Commercial license from the manufacturer.

The manufacturing company 10gen has defined MongoDB as:

"MongoDB is a scalable, open source, high performance, document-


oriented database." - 10gen

MongoDB was designed to work with commodity servers. Now it is used by


the company of all sizes, across all industry.

History of MongoDB
The initial development of MongoDB began in 2007 when the company
was building a platform as a service similar to window azure.

Window azure is a cloud computing platform and infrastructure, created by Microsoft,


to build, deploy and manage applications and service through a global network.

MongoDB was developed by a NewYork based organization named 10gen


which is now known as MongoDB Inc. It was initially developed as a PAAS
(Platform as a Service). Later in 2009, it is introduced in the market as an
open source database server that was maintained and supported by
MongoDB Inc.

The first ready production of MongoDB has been considered from version
1.4 which was released in March 2010.

MongoDB2.4.9 was the latest and stable version which was released on
January 10, 2014.

Purpose of Building MongoDB


It may be a very genuine question that - "what was the need of MongoDB
although there were many databases in action?"

There is a simple answer:


All the modern applications require big data, fast features development,
flexible deployment, and the older database systems not competent
enough, so the MongoDB was needed.

The primary purpose of building MongoDB is:

o Scalability
o Performance
o High Availability
o Scaling from single server deployments to large, complex multi-site
architectures.
o Key points of MongoDB
o Develop Faster
o Deploy Easier
o Scale Bigger

First of all, we should know what is document oriented database?

Example of Document-Oriented Database


MongoDB is a document-oriented database. It is a key feature of
MongoDB. It offers a document-oriented storage. It is very simple you can
program it easily.

MongoDB stores data as documents, so it is known as document-oriented


database.

FirstName = "John",

Address = "Detroit",

Spouse = [{Name: "Angela"}].

FirstName ="John",
Address = "Wick"

There are two different documents (separated by ".").

Storing data in this manner is called as document-oriented database.

Mongo DB falls into a class of databases that calls Document Oriented


Databases. There is also a broad category of database known as No SQL
Databases.
Features of MongoDB
These are some important features of MongoDB:

1. Support ad hoc queries

In MongoDB, you can search by field, range query and it also supports
regular expression searches.

2. Indexing

You can index any field in a document.

3. Replication

MongoDB supports Master Slave replication.

A master can perform Reads and Writes and a Slave copies data from the
master and can only be used for reads or back up (not writes)

4. Duplication of data

MongoDB can run over multiple servers. The data is duplicated to keep
the system up and also keep its running condition in case of hardware
failure.

5. Load balancing

It has an automatic load balancing configuration because of data placed in


shards.

6. Supports map reduce and aggregation tools.

7. Uses JavaScript instead of Procedures.

8. It is a schema-less database written in C++.

9. Provides high performance.

10. Stores files of any size easily without complicating your stack.

11. Easy to administer in the case of failures.

12. It also supports:

o JSON data model with dynamic schemas


o Auto-sharding for horizontal scalability
o Built in replication for high availability
o Now a day many companies using MongoDB to create new types of
applications, improve performance and availability.
MongoDB is a NoSQL Database, so it is very necessary to know about
NoSQL Database to understand MongoDB thoroughly.

What is NoSQL Database


Databases can be divided in 3 types:

1. RDBMS (Relational Database Management System)


2. OLAP (Online Analytical Processing)
3. NoSQL (recently developed database)

NoSQL Database
NoSQL Database is used to refer a non-SQL or non relational database.

It provides a mechanism for storage and retrieval of data other than


tabular relations model used in relational databases. NoSQL database
doesn't use tables for storing data. It is generally used to store big data
and real-time web applications.

History behind the creation of NoSQL Databases


In the early 1970, Flat File Systems are used. Data were stored in flat files
and the biggest problems with flat files are each company implement their
own flat files and there are no standards. It is very difficult to store data in
the files, retrieve data from files because there is no standard way to
store data.

Then the relational database was created by E.F. Codd and these
databases answered the question of having no standard way to store
data. But later relational database also get a problem that it could not
handle big data, due to this problem there was a need of database which
can handle every types of problems then NoSQL database was developed.

Advantages of NoSQL
o It supports query language.
o It provides fast performance.
o It provides horizontal scalability.

MongoDB Datatypes
Following is a list of usable data types in MongoDB.
Data Description
Types

String String is the most commonly used datatype. It is used to store data. A string m
UTF 8 valid in mongodb.

Integer Integer is used to store the numeric value. It can be 32 bit or 64 bit depending
server you are using.

Boolean This datatype is used to store boolean values. It just shows YES/NO values.

Double Double datatype stores floating point values.

Min/Max This datatype compare a value against the lowest and highest bson elements.
Keys

Arrays This datatype is used to store a list or multiple values into a single key.

Object Object datatype is used for embedded documents.

Null It is used to store null values.

Symbol It is generally used for languages that use a specific type.

Date This datatype stores the current date or time in unix time format. It makes you po
to specify your own date time by creating object of date and pass the value o
month, year into it.

http://www.mongodb.org/downloads

Start Menu > All Programs > Accessories

md\data\db

C:\Program Files\MongoDB\bin\mongod.exe

When you connect to the MongoDB through the mongo.exe shell, you
should follow these steps:

1. Open another command prompt.


2. At the time of connecting, specify the data directory if necessary.
3. C:\mongodb\bin\mongo.exe
If you use the different data directory while MongoDB installation, specify
the directory when connecting.

For example:

1. C:\mongodb\bin\mongod.exe-- dbpath d:\test\mongodb\data

If you have spaces in your path, enclose the entire path in double space.

For example:

1. C:\mongodb\bin\mongod.exe-- dbpath "d: \ test\mongodb\data"

Consider the following things while designing the schema in


MongoDB

o Always design schema according to user requirements.


o Do join on write operations not on read operations.
o Objects which you want to use together, should be combined into
one document. Otherwise they should be separated (make sure that
there should not be need of joins).
o Optimize your schema for more frequent use cases.
o Do complex aggregation in the schema.
o You should duplicate the data but in a limit, because disc space is
cheaper than compute time.

For example:

let us take an example of a client who needs a database design for his
website. His website has the following requirements:

Every post is distinct (contains unique title, description and url).

Every post can have one or more tags.

Every post has the name of its publisher and total number of likes.

Each post can have zero or more comments and the comments must
contain user name, message, data-time and likes.

For the above requirement, a minimum of three tables are required in


RDBMS.
{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user: 'COMMENT_BY',
message: TEXT,
datecreated: DATE_TIME,
like: LIKES
},
{
user: 'COMMENT_BY',
message: TEST,
dateCreated: DATE_TIME,
like: LIKES
}}}

python -m pip install pymongo

Create a database called "mydatabase":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["mydatabase"]

import pymongo

myclient = pymongo.MongoClient('mongodb://localhost:27017/')

dblist = myclient.list_database_names()
if "mydatabase" in dblist:
print("The database exists.")
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]

mycol = mydb["customers"]
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

collist = mydb.list_collection_names()
if "customers" in collist:
print("The collection exists.")

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydict = { "name": "John", "address": "Highway 37" }

x = mycol.insert_one(mydict)
mydict = { "name": "Peter", "address": "Lowstreet 27" }

x = mycol.insert_one(mydict)

print(x.inserted_id)

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mylist = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]

x = mycol.insert_many(mylist)

#print list of the _id values of the inserted documents:


print(x.inserted_ids)
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mylist = [
{ "_id": 1, "name": "John", "address": "Highway 37"},
{ "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
{ "_id": 3, "name": "Amy", "address": "Apple st 652"},
{ "_id": 4, "name": "Hannah", "address": "Mountain 21"},
{ "_id": 5, "name": "Michael", "address": "Valley 345"},
{ "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
{ "_id": 7, "name": "Betty", "address": "Green Grass 1"},
{ "_id": 8, "name": "Richard", "address": "Sky st 331"},
{ "_id": 9, "name": "Susan", "address": "One way 98"},
{ "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
{ "_id": 11, "name": "Ben", "address": "Park Lane 38"},
{ "_id": 12, "name": "William", "address": "Central st 954"},
{ "_id": 13, "name": "Chuck", "address": "Main Road 989"},
{ "_id": 14, "name": "Viola", "address": "Sideway 1633"}
]

x = mycol.insert_many(mylist)

#print list of the _id values of the inserted documents:


print(x.inserted_ids)

Find the first document in the customers collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

x = mycol.find_one()

print(x)

Return all documents in the "customers" collection, and print each document:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find():
print(x)
Return only the names and addresses, not the _ids:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):


print(x)

exclude "address" from the result:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find({},{ "address": 0 }):


print(x)

except if one of the fields is the _id field):

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find({},{ "name": 1, "address": 0 }):


print(x)

Find document(s) with the address "Park Lane 38":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Park Lane 38" }

mydoc = mycol.find(myquery)

for x in mydoc:
print(x)
Find documents where the address starts with the letter "S" or higher:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": { "$gt": "S" } }

mydoc = mycol.find(myquery)

for x in mydoc:
print(x)

Find documents where the address starts with the letter "S":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": { "$regex": "^S" } }

mydoc = mycol.find(myquery)

for x in mydoc:
print(x)

Sort the result alphabetically by name:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydoc = mycol.find().sort("name")

for x in mydoc:
print(x)

Sort the result reverse alphabetically by name:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name", -1)

for x in mydoc:
print(x)

Delete the document with the address "Mountain 21":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Mountain 21" }

mycol.delete_one(myquery)

Delete all documents were the address starts with the letter S:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": {"$regex": "^S"} }

x = mycol.delete_many(myquery)

print(x.deleted_count, " documents deleted.")

Delete all documents in the "customers" collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

x = mycol.delete_many({})

print(x.deleted_count, " documents deleted.")

Delete the "customers" collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.drop()

Change the address from "Valley 345" to "Canyon 123":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Valley 345" }


newvalues = { "$set": { "address": "Canyon 123" } }

mycol.update_one(myquery, newvalues)

#print "customers" after the update:


for x in mycol.find():
print(x)

Update all documents where the address starts with the letter "S":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": { "$regex": "^S" } }


newvalues = { "$set": { "name": "Minnie" } }

x = mycol.update_many(myquery, newvalues)

print(x.modified_count, "documents updated.")

Limit the result to only return 5 documents:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myresult = mycol.find().limit(5)

#print the result:


for x in myresult:
print(x)

You might also like