Database Connection With Python and MongoDb

 Step 1: Install Python 

Step 2 : Install MongoDb

Step 3 : Set Path For Python

Step 4 : Open CMD Command and type python








Step 5 : Command Prompt write 


Step 6 : Then Command Prompt 
               python -m pip install pymongo 


Step 7 :New Command Prompt
             64 bit system only mongo or 32 bit mongod then enter

For 32 Bit command Prompt
       mongod






 Step 8 :  command prompt write 
                show dbs

Step 9 : use database name
              use employee

Show Database name and choose database command
use database name 
eg : use employee
     and use emp
Show Table look good for command
db.emp.find().pretty()


Step 10 : Open Python IDLE and Write Code 
                  
Q. Create a Program to insert Employee Details like id, name, designation, salary into MongoDB.
  
from pymongo import MongoClient
a=MongoClient(port=27017)
db=a.employee #here, create employee database/collection
ed=input("Enter ID:")
en=input("Enter name:")
des=input("Enter designation:")
sal=float(input("Enter salary:"))
j={"eid":ed,"ename":en,"designation":des,"salary":sal}
db.emp.insert_one(j)
print("Data Added")

OUTPUT :





Q. Create a Program to search and show Employee Details by id from MongoDB.  

from pymongo import MongoClient
g=MongoClient(port=27017)
db=g.employee
ed=input("Enter employee id:")
d=db.emp.find({"eid":ed})

for j in d:
    print("Name=",j["ename"])
    print("Designation=",j["designation"])
    print("Salary=",j["salary"])

OUTPUT :





Source Video : Click Here




Comments