Introduction to MongoDB in Python
Donny Winston
Instructor
Objects {}
{'key1':value1, 'key2':value2,...}
{
'id': 12345,
'name': 'Donny Winston',
'instructor': true
},
Arrays []
[value1, value2,...]
[
"instructor_1",
"instructor_2",
...
]
{
'people': [
{ 'id': 12345,
'name': 'Donny Winston',
'instructor': true,
'tags': ['Python', 'MongoDB']
},
{ 'id': 54321
'name': 'Guido van Rossum'
'instructor':false
'tags': null
},
]
}
Values
'name':'Donny Winston'
'id': 12345
true
/false
null
'tags': ['Python', 'MongoDB']
[{ 'id': 12345, ...},...]
JSON | Python |
---|---|
Objects | Dictionaries dict |
Arrays | Lists list |
Values: | |
· strings | str |
· _numbers _ | int , float |
·true /false |
True /False |
· null |
None |
· other objects/arrays | other dict /list |
--
MongoDB | JSON | Python |
---|---|---|
Databases | Objects | Dictionaries |
↳Collections | Arrays | Lists |
↳↳Documents | Objects | Dictionaries |
↳↳↳Subdocuments | Objects | Dictionaries |
↳↳↳ Values | Value types | Value types + datetime , regex... |
import requests from pymongo import MongoClient
# Client connects to "localhost" by default client = MongoClient() # Create local "nobel" database on the fly db = client["nobel"]
for collection_name in ["prizes", "laureates"]: # collect the data from the API response = requests.get( "http://api.nobelprize.org/v1/{}.json".\ format(collection_name[:-1] )) # convert the data to json documents = response.json()[collection_name] # Create collections on the fly db[collection_name].insert_many(documents)
[]
# client is a dictionary of databases
db = client["nobel"]
# database is a dictionary of collections
prizes_collection = db["prizes"]
.
# databases are attributes of a client
db = client.nobel
# collections are attributes of databases
prizes_collection = db.prizes
# Use empty document {} as a filter
filter = {}
# Count documents in a collection
n_prizes = db.prizes.count_documents(filter)
n_laureates = db.laureates.count_documents(filter)
590
934
# Find one document to inspect
doc = db.prizes.find_one(filter)
{'_id': ObjectId('5bc56145f35b634065ba1996'),
'category': 'physics',
'laureates': [{'firstname': 'Arthur',
'id': '960',
'motivation': '"for the optical tweezers and their
application to biological systems"',
'share': '2',
'surname': 'Ashkin'},
{'firstname': 'Gérard',
'id': '961',
'motivation': '"for their method of generating
high-intensity, ultra-short optical pulses"',
...
Introduction to MongoDB in Python