- In what situations would we want to use mocks to test our code?
- If I am testing a call to an API, which function should I mock?
- Use MongoDB Compass Connect to create and view items in a database
- Get comfortable with Mongo queries
- Understand how to connect and use MongoDB in a Python web app
Document-Based Databases:
- Store data in documents similar to JSON
- Also called NoSql or non-relational because they don't use the more traditional, relational methods of storage
-
Can have several databases. Use 1 database for 1 project.
-
A database can have several collections. Each collection groups objects of the same type: User, BlogPost, Item, etc.
User
resource would be stored inusers
collectionBlogPost
resource would be stored inblog_posts
collection
-
Each collection supports CRUD operations
-
Create, Read, Update, Delete
-
Represents the operations we can do on any one type of object
-
Example - Users: Create a new user, show all users, update a user, delete a user
MongoDB gives each document a unique identification number with the key _id
.
It's sort of like dropping clothes off at the dry-cleaners: you are given a ticket with a unique identification number so that you can find your item again.
So, if we saved a new project like this to a MongoDB database:
# Python Dictionary Object
{ "title": "A New Project" }
Then it will save something like this:
# MongoDB Object
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"title": "A New Project"
}
An ObjectId is neither a string nor a number. It is a special class that we can import from bson.objectid
.
BSON stands for "bytes JSON" and is how our MongoDB data is typically stored.
>>> from bson.objectid import ObjectId
>>> my_id = ObjectId(b'foo-bar-quux')
ObjectId('666f6f2d6261722d71757578')
>>> str(my_id)
'666f6f2d6261722d71757578'
It is a desktop tool that allows us to easily create, read, update, and delete (CRUD) database objects in MongoDB. It will save you a lot of time when writing your Flask applications!
You can download it here.
- Download MongoDB Compass.
- Create a database called
test_db
with a collectionsongs
. - Enter data for your top 5 favorite songs, including the title, album, and artist.
- Practice Creating, Updating, and Deleting objects.
PyMongo is a Python library to do CRUD operations on our database from a Python app.
We can install it with:
$ pip3 install pymongo
We can access data from our database as follows:
# Import pymongo and initialize client
from pymongo import MongoClient
client = MongoClient()
# Access our database and collection
db = client['test_db']
collection = db['songs']
# Find a song
my_song = songs.find_one({'title': 'Hot N Cold'})
print(my_song)
- Create a new Python file called
songs.py
- Copy the starter code from the previous slide into the file
- Run the code!
Each CRUD operation has at least one corresponding function in PyMongo. You can read a complete list of available operations here.
CRUD Operation | PyMongo Operation |
---|---|
Create | collection.insert_one() |
Read | collection.find_one() |
Update | collection.update_one() |
Delete | collection.delete_one() |
We can read all songs, returned as a list-like object:
all_songs = songs_collection.find({'artist': 'Rihanna'})
# We can loop over this just like a list
for song in all_songs:
print(song)
Or query for only one song:
song = songs_collection.find_one({'title': 'Umbrella'})
print(song)
Create a JSON object containing the data, then call insert_one
.
new_song = {
'name': 'Hot N Cold',
'artist': 'Katy Perry',
'rating': 5
}
result = songs_collection.insert_one(new_song)
Here, we must pass in a JSON object with the field $set
.
query = {'title': 'Hot N Cold'}
new_values = {
'$set': {
'rating': 4
}
}
result = songs_collection.update_one(query, new_values)
query = {'title': 'Friday'}
result = songs_collection.delete_one(query)
In your songs.py
program, complete the following:
- Create another song and put it into the database
- Print a list of all songs
- Find a song with a particular title, and print it
- Update a song with a new artist or rating
- Delete a song
Go to https://make.sc/bew1.1-vibe-check and fill out the form.
Have any shout-outs? Show appreciation for your peers!
- Start on the Playlister tutorial - due Tuesday, Nov. 26
- Quiz on Thursday covering APIs, JSON, & Testing