Assignment16Utkarsh
Assignment16Utkarsh
Question 1
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.
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.
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.
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:
Question 3
Answer :
1. Installing pymongo
In [1]:
%pip install 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)
3. Creating a database
In [4]:
db = client['example_db']
4. Creating a collection
In [5]:
my_coll = db['my_collection']
Question 4
Answer:
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>
In [8]:
my_coll.find_one()
Out[8]:
{'_id': ObjectId('63efccae98a41ff612486b9d'),
'firstName': 'Utkarsh',
'lastName': 'Gaikwad',
'age': 28,
'email': '[email protected]',
'phone': 129434324,
'favouriteSubject': 'calculus'}
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>
In [11]:
for i in my_coll.find():
print(i)
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.
In [12]:
for i in my_coll.find({'_id':{'$gte':2}}):
print(i)
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).
In [13]:
result = my_coll.find().sort("_id",-1)
for i in result:
print(i)
In above example if I want to sort list in ascending order then : my_coll.find().sort("_id",1) is used
Question 7
1. delete_one:
In [14]:
# Checking all data in my_coll
for i in my_coll.find():
print(i)
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)
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)
3. drop
In [19]:
my_coll.drop()
In [20]:
for i in my_coll.find():
print(i)
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()