Python3 Examples With MongoDB Using PyMongo

1. Python3 Code To Insert One Document And Get One Document From MongoDB Using PyMongo Api.

from pymongo import MongoClient  
import pprint  

client = MongoClient()  
  
db = client.kkar
  
employee = {"id": "1","name": "a","profession": "SE"}  
   
emp = db.employees  
 
emp.insert_one(employee)  
pprint.pprint(emp.find_one()) 

2. Python3 Code To Select All Documents From MongoDB Using PyMongo Api.

from pymongo import MongoClient  
import pprint  
client = MongoClient()  
 
db = client.kkar
   
emp = db.employees.find({});  

for a in emp:
	pprint.pprint(a) 

3. Python3 Code To Select All Documents From MongoDB Based On Condition Using PyMongo Api.

from pymongo import MongoClient  
import pprint  
client = MongoClient()  
 
db = client.kkar
   
emp = db.employees.find({"id":"1"}).skip(1);  

for a in emp:
	pprint.pprint(a) 

4. Python3 Code To Delete Documents From MongoDB Based On Condition Using PyMongo Api.

from pymongo import MongoClient  
import pprint  
client = MongoClient()  
 
db = client.kkar
   
#emp = db.employees.remove();  
 emp = db.employees.remove({"id":"1"}); 

5. Python3 Code To Update One Document In MongoDB Based On Condition Using PyMongo Api.

from pymongo import MongoClient  
import pprint  
client = MongoClient()  
 
db = client.kkar
   
emp = db.employees.update_one({"id":"1"},{"$set":{'name':'testing'}}); 

6. Python3 Code To drop the collection In MongoDB Using PyMongo Api.

from pymongo import MongoClient  
import pprint  
client = MongoClient()  
 
db = client.kkar
   
emp = db.employees.drop(); 

7. Python3 Code To drop the data In MongoDB Using PyMongo Api.

from pymongo import MongoClient  
import pprint  
client = MongoClient()  
 
db = client.kkar
   
db.drop("kkar"); 

Leave a Comment