Pymongo Detailed Revision v2
1. Accessing MongoDB Database and printing database names
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
dbs = client.list_database_names()
for i in dbs:
print(i)
client.close()Output:
admin
booksdb
hrdb
lang
library
local
movieDB
mydatabase
restdb
test
test_info2. Printing collections from within the database
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['test_info']
coll = db['fruit']
db.list_collection_names()Output:
['fruits', 'fruit', 'student', 'person']3. Inserting Data
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['test_info']
coll = db['fruit']
result = coll.insert_one({'name': 'hello', 'qty':321})
print(result.inserted_id)Output:
60d8318b8258a00fb8f81173import json
from pymongo import MongoClient
myfile = open(r'Restaurants\intern.json','r')
fileLines= myfile.readlines()
fileString = ''
for i in fileLines:
i.strip('\n')
i.strip('\t')
fileString += i
internDictionary = json.loads(fileString)
internDictionary = internDictionary['intern_details']
print(internDictionary)
print(type(internDictionary))
client = MongoClient('localhost', 27017)
db = client['test_info']
coll = db['person']
x = coll.insert_many(internDictionary)
print(x.inserted_ids)Output:
[{'name': 'Tan Tan Tan', 'email': 'tttan@lotsofintern.com', 'designation': 'intern'}, {'name': 'Lee Lee Lee', 'email': 'lllee@lotsofintern.com', 'designation': 'intern'}, {'name': 'Ng Ng Ng', 'email': 'nnng@lotsofintern.com', 'designation': 'intern'}]
<class 'list'>
[ObjectId('60d84380ed88c99d19911db1'), ObjectId('60d84380ed88c99d19911db2'), ObjectId('60d84380ed88c99d19911db3')]4. Data Querying
from pymongo import MongoClient
client = MongoClient("localhost", 27017)
db = client['test_info']
coll = db['fruit']
query = {'name':{'$regex':'an'}, 'qty':{'$gte':20}}
query = {'address.coords.0':1.3042}
projection ={'_id':0}
x = coll.find(query, projection)
for i in x:
print(i)Output:
{'name': 'watermelon', 'qty': 31, 'address': {'state': 'singapore', 'postal': 551221, 'coords': [1.3042, 103.8392]}}5. Updating Data (Set)
from pymongo import MongoClient
client = MongoClient('localhost',27017)
db = client['test_info']
print(db.list_collection_names())
coll = db['fruits']
query = {'name':'together'}
proj = {'$set':{'name':'applebananatogether'}}
x = coll.update_many(query, proj)
print(x.modified_count)
# for i in x:
# print(i)
client.close()Output:
['fruits', 'fruit', 'student', 'person']
26. Sorting
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['test_info']
coll = db['fruit']
query = {'qty':{'$exists':True}, 'country':{'$exists':False}}
proj = {'_id':0, 'address':0}
x = coll.find(query, proj).sort('name',-1)
# The negative 1 makes the sort sorted in reverse alphabetical
for i in x:
print(i)Output:
{'name': 'watermelon', 'qty': 31}
{'name': 'pear', 'qty': 15.0}
{'name': 'orange', 'qty': 20.0}
{'name': 'hello', 'qty': 321}
{'name': 'hello', 'qty': 321}
{'name': 'hello', 'qty': 321}
{'name': 'grapefruit', 'qty': 1}
{'name': 'durian', 'qty': 5.0}
{'name': 'applebananatogether', 'qty': 100}
{'name': 'applebananatogether', 'qty': 100}
{'name': 'apple', 'qty': 10.0}from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['test_info']
coll = db['fruit']
#remember thisssssss
query = {'$or':[{'name':'hello'}, {'name':'durian'}]}
query = {'name':{'$in':['hello', 'orange']}}
query = {'name':{'$in':['hello', 'orange']}}
query = {"qty":{"$not":{"$gt":10}}}
projection = {'_id':0}
x = coll.find(query, projection)
for i in x:
print(i)Output:
{'name': 'apple', 'qty': 10.0}
{'name': 'durian', 'qty': 5.0}
{'name': 'lemon', 'qty': '10', 'country': 'SA'}
{'name': 'lime', 'qty': '15', 'country': 'SG'}
{'name': 'apple', 'qty': '40', 'country': 'SG'}
{'name': 'apple', 'qty': '30', 'country': 'SA'}
{'name': 'grape', 'qty': 10, 'country': 'SG'}
{'name': 'grapefruit', 'qty': 1}7. Misc:
# useful one-liner python scripts
with open('test.txt', 'r') as file: lines = file.readlines()
lines = [i.strip('\n') for i in lines]
print(lines)
alphabets = [chr(i) for i in range(65,91)]
print(alphabets)Output:
['line1', '2', '3', '5', '76', '213']
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']