You are on page 1of 23

Database Interaction

• NoSQL
NoSQL databases (aka "not only SQL") are non-tabular databases and store
data differently than relational tables. NoSQL databases come in a variety of
types based on their data model. The main types are document, key-value,
wide-column, and graph. They provide flexible schemas and scale easily with
large amounts of data and high user loads.

A NoSQL database provides a mechanism for storage and retrieval of data


that is modeled in means other than the tabular relations used in relational
databases.
SQL vs NoSQL
SQL is the programming language used to interface with relational databases.
(Relational databases model data as records in rows and tables with logical
links between them). NoSQL is a class of DBMs that are non-relational and
generally do not use SQL.
There are five practical differences between SQL and NoSQL:
1. Language
2. Scalability
3. Structure
4. Properties
5. Support and communities
1. Language
The dynamic schema of NoSQL databases allow representation of
alternative structures, often alongside each other, encouraging greater
flexibility. There is less emphasis on planning, greater freedom when
adding new attributes or fields, and the possibility of varied syntax
across databases. As a group, however, NoSQL languages lack the
standard interface which SQL provides, so more complex queries can
be difficult to execute.
Though there are many dialects of SQL, all share a common syntax and
almost-identical grammar. When querying relational databases,
fluency in one language translates to proficiency in most others. On
the other hand, there is very little consistency between NoSQL
languages, as they concern a diverse set of unrelated technologies.
Many NoSQL databases have a unique data manipulation language
constrained by particular structures and capabilities.
2. Scalability
• Most SQL databases can be scaled vertically, by increasing the
processing power of existing hardware. NoSQL databases use a
master-slave architecture which scales better horizontally, with
additional servers or nodes. These are useful generalizations, but
it’s important to note:
• SQL databases can be scaled horizontally as well, though sharding
or partitioning logic is often the user’s onus and not well supported.
• NoSQL technologies are diverse and while many rely on the master-
slave architecture, options for scaling vertically also exist.
• Savings made using more efficient data structures can overwhelm
differences in scalability; most important is to understand the use
case and plan accordingly.
• 3. Structure
• SQL database schemata always represent relational, tabular data,
with rules about consistency and integrity. They contain tables with
columns (attributes) and rows (records), and keys have constrained
logical relationships.
• NoSQL databases need not stick to this format, but generally fit into
one of four broad categories:
• Column-oriented databases transpose row-oriented RDBMSs,
allowing efficient storage of high-dimensional data and individual
records with varying attributes.
• Key-Value stores are dictionaries which access diverse objects with
a key unique to each.
• Document stores hold semi-structured data: objects which contain
all of their own relevant information, and which can be completely
different from each other.
• Graph databases add the concept of relationships (direct links
between objects) to documents, allowing rapid traversal of greatly
connected data sets.
• 4. Properties
• At a high level, SQL and NoSQL comply with separate rules for
resolving transactions. RDBMSs must exhibit four “ACID” properties:
• Atomicity means all transactions must succeed or fail completely.
They cannot be partially-complete, even in the case of system
failure.
• Consistency means that at each step the database follows
invariants: rules which validate and prevent corruption.
• Isolation prevents concurrent transactions from affecting each
other. Transactions must result in the same final state as if they
were run sequentially, even if they were run in parallel.
• Durability makes transactions final. Even system failure cannot roll-
back the effects of a successful transaction.
• 5. Support and communities
• SQL databases represent massive communities, stable codebases,
and proven standards. Multitudes of examples are posted online
and experts are available to support those new to programming
relational data.
• NoSQL technologies are being adopted quickly, but communities
remain smaller and more fractured. However, many SQL languages
are proprietary or associated with large single-vendors, while
NoSQL communities benefit from open systems and concerted
commitment to onboarding users.
• SQL is available to most major platforms, from operating systems to
architectures and programming languages. Compatibility varies
more widely for NoSQL, and dependencies need to be investigated
more carefully.
• Top advantages of NoSQL databases
• Flexible scalability. ...
• Flexible data types. ...
• Large amounts of data storage. ...
• Simplicity and less code. ...
• Less ongoing database maintenance. ...
• Queries are less flexible. ...
• Less mature. ...
• NoSQL isn't designed to scale by itself.
• Python MongoDB Connectivity
To create connection between Python programming language and
MongoDB database, we need to first install pymongo driver. Here, we
are creating an example that connects to the database and performs
basic database operations.
This example includes the following steps:
1) Install Driver

2) Create Python File


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

# Creating database
mydb = myclient["xyz"]
mycol = mydb["test"]
print(mydb.list_collection_names())
• In MongoDB, a collection is not created until it gets content, so if
this is your first time creating a collection, you should complete the
create document before you check if the collection exists!
• You can check if a collection exist in a database by listing all
collections:
• mydict = { "name": "John", "address": "Highway 37" }
• x = mycol.insert_one(mydict)
• print(x.inserted_id)

• Return a list of all collections in your database:


• print(mydb.list_collection_names())
you can check a specific collection by name:
collist = mydb.list_collection_names()
if "startup_log" in collist:
print("The collection exists.")

• MongoDB CRUD operations


Create Operations –
The create or insert operations are used to insert or add new
documents in the collection. If a collection does not exist, then it will
create a new collection in the database. You can perform, create
operations using the following methods provided by the MongoDB:

Method Description
It is used to insert a single
db.collection.insertOne()
document in the collection.
It is used to insert multiple
db.collection.insertMany()
documents in the collection.
It is used to create an empty
db.createCollection()
collection.
• Read Operations –
• The Read operations are used to retrieve documents from the
collection, or in other words, read operations are used to query a
collection for a document. You can perform read operation using
the following method provided by the MongoDB:

It is used to retrieve documents from the


db.collection.find()
collection.
• Update Operations –
• The update operations are used to update or modify the existing
document in the collection. You can perform update operations
using the following methods provided by the MongoDB:

Method Description
It is used to update a single document in
db.collection.updateOne() the collection that satisfy the given
criteria.
It is used to update multiple documents in
db.collection.updateMany() the collection that satisfy the given
criteria.
It is used to replace single document in
db.collection.replaceOne() the collection that satisfy the given
criteria.
• Delete Operations –
• The delete operation are used to delete or remove the documents
from a collection. You can perform delete operations using the
following methods provided by the MongoDB:

Method Description

It is used to delete a single document


db.collection.deleteOne() from the collection that satisfy the given
criteria.

It is used to delete multiple documents


db.collection.deleteMany() from the collection that satisfy the given
criteria.
• Steps for connectivity
• 1. Installation-
• Do installation with few steps.
• Update system path variable in environment variables options.
• Copy C:\Program Files\MongoDB\Server\5.0\bin
• To new path
• Create C:\Program Files\data\db folders
• Open command prompt
• Type mongod
• Type mongo
• Open mongodb Compass
• Connect localhost:27017

• Example—
• import pymongo
• myclient = pymongo.MongoClient("mongodb://localhost:27017/")

• #create database
• mydb = myclient["employee"]

• #crate collection
• mycol = mydb["emp"]

• #add records
• mydict = [{ "name": "Rahul", "empid": "0001" , "designation":"developer"},
• {"name": "Amit", "empid": "0002" , "designation":"lead"},
• {"name": "Vijay", "empid": "0003" , "designation":"tester"}]

• x = mycol.insert_many(mydict)
• #find records
• myquery = { "name": "Rahul" }
• mydoc = mycol.find(myquery)
• for x in mydoc:
• print(x)

• #Delete records
• mycol.delete_one(myquery)
• x = mycol.delete_many(myquery)
• print(x.deleted_count, " documents deleted.")

• #Update records
• myquery = { "empid": "0003" }
• newvalues = { "$set": { "name": "Santosh" } }

• mycol.update_one(myquery, newvalues)
• for x in mycol.find():
• print(x)

You might also like