Mongo DB
Reference: https://docs.mongodb.com/
1) Installing MongoDB¶
goto https://www.mongodb.com/try/download/community
and download based on your OS.
2) double click on the downloaded file to install.
2) Starting MongoDB
1. Go the services section and then start the MongoDB service if not already started
2. Go to bin directory of the MongoDB installation and run the ‘mongo’ command
C:\>cd Program Files\MongoDB\Server\4.4\bin
If command runs successfully, it means the server is up and running.
3) MongoDB Basics:
Difference Between MongoDB and Relational DB
| MongoDB | RDBMS |
|---|---|
| Database | Database |
| Collection | Table |
| Document | Row |
| Field | column |
| Embedded Documents | Table Join |
| Primary Key (Default key "_id" ) | Primary Key |
4) Basic Commands
show dbs: to show all the databases
use <DBName>: creates a new database with the name if not already present or starts using the database given as database name.
db.createCollection(‘<collectionName>’) : to create a new collection. Collections are analogous to tables.
show collections to show all the collections in a database.
db.<collectionName>.insert({“key”:”value”}) : to insert new record into the table.
db.<collectionName>.find(): To show all the records from a table.
db.<collectionName>.update({“key”:”value”}, ({“key”:”new_value”}) : to update an existing record in the table.
db.<collectionName>.remove({“key”:”value”}) : to remove record(s) from the table matching the criteria.
5) Using python for MongoDB
Install Pymongo library
pip install pymongo
import pymongo
dbConn = pymongo.MongoClient("mongodb://localhost:27017/")
# connecting to the locally running MongoDB Instance
dbname='hk_DB1'
db = dbConn[dbname] # connecting to the database named hkDB1 present in the mongoDB
# if the database is not present, it'll autoamtically create it.# show all the databases
print(dbConn.list_database_names())
o/p:
['admin', 'config', 'hk_DB1', 'local']
# check if the databse exists in mongoDB
dblist=dbConn.list_database_names() # obtaining all the database names
db_name='hk_DB1'
if dblist.index(db_name)==-1:
print ("This Databse doesn't exist")
else:
print ("This Databse exists")
o/p:
This Databse exists
# connecting to a collection(collections are tables in MongoDB)
collection_name='hk_collection1'
collection=db[collection_name] # connectig to the collection
# cheking if a collection exists
if collection_name in db.list_collection_names():
print("The collection exists.")
else:
print("The collection doesn't exist.")
O/p:
The collection exists.
# inserting a row into collection
hk_row1 = {'id': '1234',
'name': 'hk',
'profession': 'SE'
} # creating key value pairs for inserting into the DB
x = collection.insert_one(hk_row1) # inserting record into the collection
x.inserted_id #gives unique of insert
O/P:
ObjectId('6059d389bb9fd7f87181318d')
# inserting multiple rows once
hk_rows = [
{'id': '1234',
'name': 'hk',
'profession': 'SE'},
{
'id': '5678',
'name': 'ab',
'profession': 'associate'},
{'id': '9123',
'name': 'bc',
'profession': 'lead'}
]
# inserting multiple records into the collection
x = collection.insert_many(hk_rows)
# retieving specific record from collection
result= collection.find({})
result[1] #printing the third record
O/p:
{'_id': ObjectId('6059d4c2bb9fd7f871813192'),
'id': '5678',
'name': 'ab',
'profession': 'associate'}
# find brings out all the records, to overcoem this use limit
result_total= collection.find({}).limit(2)
for res in result_total:
print(res)
O/p:
{'_id': ObjectId('6059d4c2bb9fd7f871813191'), 'id': '1234', 'name': 'hk', 'profession': 'SE'}
{'_id': ObjectId('6059d4c2bb9fd7f871813192'), 'id': '5678', 'name': 'ab', 'profession': 'associate'}
# retrieveing specific columns
result_some= collection.find({}, {'id','name'}).limit(2) # retrieveing two columns
# The second parameter in find() specifies which columns to choose
for res in result_some:
print(res)
O/p:
{'_id': ObjectId('6059d4c2bb9fd7f871813191'), 'id': '1234', 'name': 'hk'}
{'_id': ObjectId('6059d4c2bb9fd7f871813192'), 'id': '5678', 'name': 'ab'}
# finding the rows based on given criteria
my_db_query={'name':'hk'}
result1= collection.find(my_db_query) # printing rows where name = hk
for res in result1:
print(res)
O/p:
{'_id': ObjectId('6059d4c2bb9fd7f871813191'), 'id': '1234', 'name': 'hk', 'profession': 'SE'}
# Deleting records from mongo DB:
# finding the rows based on given conditon
my_db_query={'name':'hk'}
x=collection.delete_one(my_db_query) # the deletion step
print(x.deleted_count)



No comments:
Post a Comment