Pymongo Detailed Revision

Pymongo Revision

NOTE: This will not work without your own local instance of mongod being open. My code uses the database test_info with collections of fruit, fruits, and person

1. Accessing MongoDB Database and printing database names

from pymongo import MongoClient
client = MongoClient("localhost",  27017)
 
dbs = client.list_database_names()
for d in dbs:
    print(d)
client.close()

Output:

admin
booksdb
hrdb
lang
library
local
movieDB
mydatabase
restdb
test
test_info

2. 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':'applebananatogether','qty':100})
# insert_one requires to be in the form of a dictionary
print(result.inserted_id)
# this checks if it has been inserted (honestly i dont think this is very useful)
 
coll.insert_many([
    {'name':'banana', 'qty':100},
    {'name':'grape', 'qty':10, 'country':'SG'},
    {'name':'grapefruit', 'qty':1},
    {'name':'watermelon', 'qty':31, 'address':{'state':'singapore', 'postal':551221, 'coords':(1.3042,103.8392)}},
])

Output:

60c8862dde6aad62ca0cb589

Output:

<pymongo.results.InsertManyResult at 0x18357011900>
import json
from pymongo import MongoClient
 
myfile = open(r'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('60d84401ab9c2a03131e7042'), ObjectId('60d84401ab9c2a03131e7043'), ObjectId('60d84401ab9c2a03131e7044')]

4. Data Querying

# list of queries
queries = {
'all' : {},
'string_regex' : {'name':{'$regex':"apple"}}, #results such as "applebananatogether" would be returned.
'query2' : {'name':"apple"}, # only results matching 'apple' as whole word would be displayed
 
'name_in' : {'name':{'$in':["apple", "banana"]}},
'name_notin' : {'name':{'$nin':["apple", "banana"]}},
 
'country_exist' : {'country':{'$exists':True}},
 
'qty_eq' : {'qty':{'$eq':100}},
'qty_noteq' : {'qty':{'$ne':100}},
'qty_gte' : {'qty':{'$gte':100}},
# other commands : $gt, $lt, $lte,
 
## MORE COMPLEX QUERIES:
# e.g when data is: {'name': 'watermelon', 'qty': 31, 'address': {'state': 'singapore', 'postal': '551221', 'coords': [1.3042, 103.8392]}}
 
'dict_within_dict' : {'address.state':'singapore'},
'list_within_dict_and_dict' : {'address.coords.0':1.3042}}

Queries tester:

there really should have been an easier way to do this

from pymongo import MongoClient
client = MongoClient("localhost", 27017)
 
db = client['test_info']
coll = db['fruit']
 
optionString = "01: all\n02: string regex\n03: string whole\n04: in\n05: not in\n06: exists\n07: equal\n08: not equal\n09: greater than equal\n10: dict within dict \n11: list within dict within dict"
indexedQueries = list(queries.keys())
 
choice = '1'
proj = {'_id':0}
while choice != 'end':
    if choice == 'option':
        print(optionString, '\n')
    else:
        index = int(choice)
        index -= 1
        print(f"search: {indexedQueries[index]}")
        x = coll.find(queries[f"{indexedQueries[index]}"],proj)
        for i in x: print(i)
        print('')
    choice = str(input('Choose option num: (end to kill, options to view)'))
 
client.close()

Output:

search: all
{'name': 'apple', 'qty': 10.0}
{'name': 'orange', 'qty': 20.0}
{'name': 'pear', 'qty': 15.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': 'applebananatogether', 'qty': 100}
{'name': 'applebananatogether', 'qty': 100}
{'name': 'banana', 'qty': 100}
{'name': 'grape', 'qty': 10, 'country': 'SG'}
{'name': 'grapefruit', 'qty': 1}
{'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']
coll = db['fruit']
 
query = {'name':'APPLE'}
newvalue = {'$set':{'name':'apple'}}
# take note: newvalue has a dict within dict, key of $set, key of inner dict is the var name.
x = coll.update_many(query,newvalue)
print(x.modified_count)
 
 
# deleting data
query = {'name':'banana'}
query_all = {}
# y = coll.delete_many(query_all) # deletes all 
# y = coll.delete_one
y = coll.delete_many(query)
print(y.deleted_count)
 
client.close()

Output:

3
1

6. Sorting

7. Misc:

# json imports (TBI)
# 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']