0% found this document useful (0 votes)
14 views

Assignment16Utkarsh

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Assignment16Utkarsh

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Assignment 16: MongoDB - Utkarsh Gaikwad

Assignment pdf link

Question 1

Question 1: What is MongoDB? Explain non-relational databases in


short. In which scenarios it is preferred to use MongoDB over SQL
databases?

Answer :
MongoDB is a popular open-source NoSQL database system that stores data in a document-oriented format.
Instead of using tables and rows like in traditional relational databases, MongoDB stores data in documents that
are organized into collections. These documents can contain a variety of data types, such as arrays and nested
documents, and can be easily updated and queried.These documents are stored in bson (binary JSON) format.

Non-relational databases, also known as NoSQL databases, are databases that do not use the traditional table-
based relational database model. Instead, they use different data models, such as key-value, document-
oriented, or graph-based, to store and organize data. Non-relational databases are often used for handling large
amounts of unstructured or semi-structured data, and they can be more flexible and scalable than traditional
SQL databases.

MongoDB is preferred over SQL databases in scenarios where:

1. Flexibility and scalability are important: MongoDB is designed to be flexible and scalable, making it a good
choice for handling large and complex data sets.
2. Agile development: MongoDB's flexible schema allows for more agile and iterative development, as changes
can be made to the database schema without requiring a complete redesign of the application.
3. Big Data and real-time analytics: MongoDB is well-suited for big data and real-time analytics, as it can easily
handle unstructured and semi-structured data.
4. Cloud-based applications: MongoDB is often used for cloud-based applications, as it can easily scale to
meet the demands of a growing user base.
5. Geospatial data: MongoDB has built-in support for geospatial data, making it a popular choice for
applications that involve location-based services.

Credits for above image : https://www.upwork.com/resources/nosql-vs-sql

Question 2
Question 2: State and Explain the features of MongoDB.

Answer :
In MongoDB, data is organized into a hierarchy of databases, collections, and documents.

1. A database is a container for a set of collections, each with its own set of documents. In MongoDB, you can
have multiple databases within a single MongoDB server instance.
2. A collection is a group of MongoDB documents, similar to a table in a relational database. Collections are
used to group related documents together and typically have a common schema, although MongoDB's
flexible document model allows for some variation within a collection. Each collection within a MongoDB
database is given a unique name that is used to identify and access the collection.
3. A document is a set of key-value pairs that is stored within a collection. In MongoDB, a document is similar
to a record in a relational database, but it is stored in a flexible and dynamic format known as BSON (Binary
JSON). Each document can have its own unique structure and can include nested sub-documents and
arrays.

Credits for above image : https://studio3t.com/academy/lessons/mongodb-basics/

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.
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:

JSON data model with dynamic schemas


Auto-sharding for horizontal scalability
Built in replication for high availability

Question 3

Question 3: Write a code to connect MongoDB to Python. Also, create a


database and a collection in MongoDB.

Answer :

1. Installing pymongo

In [1]:
%pip install pymongo

Requirement already satisfied: pymongo in e:\pwskills assignments\venv\lib\site-packages


(4.3.3)
Requirement already satisfied: dnspython<3.0.0,>=1.16.0 in e:\pwskills assignments\venv\l
ib\site-packages (from pymongo) (2.3.0)
Note: you may need to restart the kernel to use updated packages.

2. Connect to mongoDB with MongoClient() method of pymongo

In [2]:
import pymongo
client = pymongo.MongoClient("mongodb+srv://gaikwadujg:[email protected].
mongodb.net/?retryWrites=true&w=majority")

In [3]:
client
Out[3]:

MongoClient(host=['ac-ip2cc7c-shard-00-02.7chcxpg.mongodb.net:27017', 'ac-ip2cc7c-shard-0
0-00.7chcxpg.mongodb.net:27017', 'ac-ip2cc7c-shard-00-01.7chcxpg.mongodb.net:27017'], doc
ument_class=dict, tz_aware=False, connect=True, retrywrites=True, w='majority', authsourc
e='admin', replicaset='atlas-oqagtt-shard-0', tls=True)

Connection successfully established with MongoDB Atlas

3. Creating a database

In [4]:
db = client['example_db']

4. Creating a collection

In [5]:
my_coll = db['my_collection']

Question 4

Question 4 : Using the database and the collection created in question


number 3, write a code to insert one record, and insert many records.
Use the find() and find_one() methods to print the inserted record.

Answer:

1. Inserting a single record

In [6]:
data1 = { 'firstName':'Utkarsh',
'lastName':'Gaikwad',
'age':28,
'email':'[email protected]',
'phone':129434324,
'favouriteSubject':'calculus'}

In [7]:
my_coll.insert_one(data1)
Out[7]:
<pymongo.results.InsertOneResult at 0x2fd87676f80>

2. Printing above record with find_one()

In [8]:
my_coll.find_one()
Out[8]:
{'_id': ObjectId('63efccae98a41ff612486b9d'),
'firstName': 'Utkarsh',
'lastName': 'Gaikwad',
'age': 28,
'email': '[email protected]',
'phone': 129434324,
'favouriteSubject': 'calculus'}

3. Inserting multiple records

In [9]:
data2 = [{'_id':1,'function':'sin(x)','derivative':'cos(x)','inverse':'asin(x)'},
data2 = [{'_id':1,'function':'sin(x)','derivative':'cos(x)','inverse':'asin(x)'},
{'_id':2,'function':'cos(x)','derivative':'-sin(x)','inverse':'acos(x)'},
{'_id':3,'function':'tan(x)','derivative':'sec^2(x)','inverse':'atan(x)'}]

In [10]:
my_coll.insert_many(data2)

Out[10]:
<pymongo.results.InsertManyResult at 0x2fd87677880>

4. Viewing results with find() method

In [11]:
for i in my_coll.find():
print(i)

{'_id': ObjectId('63efccae98a41ff612486b9d'), 'firstName': 'Utkarsh', 'lastName': 'Gaikwa


d', 'age': 28, 'email': '[email protected]', 'phone': 129434324, 'favouriteSubject': 'calculu
s'}
{'_id': 1, 'function': 'sin(x)', 'derivative': 'cos(x)', 'inverse': 'asin(x)'}
{'_id': 2, 'function': 'cos(x)', 'derivative': '-sin(x)', 'inverse': 'acos(x)'}
{'_id': 3, 'function': 'tan(x)', 'derivative': 'sec^2(x)', 'inverse': 'atan(x)'}

Question 5

Question 5: Explain how you can use the find() method to query the
MongoDB database. Write a simple code to demonstrate this.

Answer :
The find() method is used to query a MongoDB database and retrieve data from a specific collection. It allows
you to search for documents in the collection that match a specific set of criteria, such as a particular value in a
field, a range of values, or a regular expression pattern.

The find() method takes an optional query object as its argument, which defines the criteria for the search. This
query object is typically constructed using a set of key-value pairs, where each key represents a field in the
document and each value represents the value to search for in that field. The find() method returns a cursor to
the resulting documents, which can be iterated over to access the data.

Example: Finding _id>=2 in my_coll collection created in question 4

In [12]:
for i in my_coll.find({'_id':{'$gte':2}}):
print(i)

{'_id': 2, 'function': 'cos(x)', 'derivative': '-sin(x)', 'inverse': 'acos(x)'}


{'_id': 3, 'function': 'tan(x)', 'derivative': 'sec^2(x)', 'inverse': 'atan(x)'}

Question 6
Question 6: Explain the sort() method. Give an example to demonstrate
sorting in MongoDB.

Answer :
The sort() method in pymongo is used to sort the results of a query in MongoDB. It allows you to specify one or
more fields to sort by, as well as the order in which to sort them (ascending or descending).

Example: sorting _id in Descending order from my_coll

In [13]:
result = my_coll.find().sort("_id",-1)
for i in result:
print(i)

{'_id': ObjectId('63efccae98a41ff612486b9d'), 'firstName': 'Utkarsh', 'lastName': 'Gaikwa


d', 'age': 28, 'email': '[email protected]', 'phone': 129434324, 'favouriteSubject': 'calculu
s'}
{'_id': 3, 'function': 'tan(x)', 'derivative': 'sec^2(x)', 'inverse': 'atan(x)'}
{'_id': 2, 'function': 'cos(x)', 'derivative': '-sin(x)', 'inverse': 'acos(x)'}
{'_id': 1, 'function': 'sin(x)', 'derivative': 'cos(x)', 'inverse': 'asin(x)'}

In above example if I want to sort list in ascending order then : my_coll.find().sort("_id",1) is used

Question 7

Question 7 : Explain why delete_one(), delete_many(), and drop() is


used.

Answer : delete_one(), delete_many(), and drop() are methods used in


pymongo to remove documents and collections from a MongoDB
database.
1. delete_one(filter, collation=None) deletes a single document from the specified collection that matches the
given filter criteria.
2. delete_many(filter, collation=None) deletes all documents from the specified collection that match the given
filter criteria.
3. drop() removes an entire collection from the database.

1. delete_one:

In [14]:
# Checking all data in my_coll
for i in my_coll.find():
print(i)

{'_id': ObjectId('63efccae98a41ff612486b9d'), 'firstName': 'Utkarsh', 'lastName': 'Gaikwa


{'_id': ObjectId('63efccae98a41ff612486b9d'), 'firstName': 'Utkarsh', 'lastName': 'Gaikwa
d', 'age': 28, 'email': '[email protected]', 'phone': 129434324, 'favouriteSubject': 'calculu
s'}
{'_id': 1, 'function': 'sin(x)', 'derivative': 'cos(x)', 'inverse': 'asin(x)'}
{'_id': 2, 'function': 'cos(x)', 'derivative': '-sin(x)', 'inverse': 'acos(x)'}
{'_id': 3, 'function': 'tan(x)', 'derivative': 'sec^2(x)', 'inverse': 'atan(x)'}

In [15]:
# Example 1: delete_one()
my_coll.delete_one({'firstName':'Utkarsh'})
Out[15]:
<pymongo.results.DeleteResult at 0x2fd87677c10>

In [16]:
# Viewing collection after delete_one()
for i in my_coll.find():
print(i)

{'_id': 1, 'function': 'sin(x)', 'derivative': 'cos(x)', 'inverse': 'asin(x)'}


{'_id': 2, 'function': 'cos(x)', 'derivative': '-sin(x)', 'inverse': 'acos(x)'}
{'_id': 3, 'function': 'tan(x)', 'derivative': 'sec^2(x)', 'inverse': 'atan(x)'}

2. delete_many, deleting id>=2

In [17]:
my_coll.delete_many({'_id':{'$gte':2}})
Out[17]:
<pymongo.results.DeleteResult at 0x2fd87676230>

In [18]:
# Viewing the my_coll after delete_many
for i in my_coll.find():
print(i)

{'_id': 1, 'function': 'sin(x)', 'derivative': 'cos(x)', 'inverse': 'asin(x)'}

3. drop

In [19]:
my_coll.drop()

In [20]:
for i in my_coll.find():
print(i)

Closing MongoDB Connection

It's a good practice to close the connection once you're done with the
database operations to avoid any memory leaks or unwanted
connections.
In [21]:
client.close()

You might also like