Start learning free

LESSON 50 OF 66 · NOSQL: MONGODB

Documents, Not Rows in Python

Practice

In SQL, every product is a row with the same fixed columns. In MongoDB, every product is a document: a set of fields and values, just like a Python dict. A field can hold a list, or even a dict of its own, and the documents in one collection (MongoDB's word for a table) don't all need the same fields.

You talk to MongoDB with the pymongo library. This lesson runs on an in-memory MongoDB that already holds the shop; the same code runs unchanged on a real MongoDB server. find_one(filter) gives back the first document that matches the filter, as a dict, or None when nothing matches. The filter is a dict of fields and the values they must have, like a WHERE. insert_one(doc) adds one dict, and count_documents(filter) counts the matches. For example, on the customers:

ana = db.customers.find_one({"email": "ana@example.com"})
print(ana["city"])
db.customers.insert_one({"_id": 6, "name": "Zoe", "phones": ["555-0101", "555-0102"]})
print(db.customers.count_documents({}))

The empty filter {} matches every document, like a COUNT(*) with no WHERE. A list field comes back as a Python list, and a dict inside a document is read one pair of square brackets at a time.

Your script must print these 4 lines:

{'_id': 1, 'name': 'Mug', 'price': 12, 'category': 'kitchen', 'tags': ['gift', 'ceramic'], 'stock': {'count': 10, 'warehouse': 'A'}}
10 ['gift', 'ceramic']
9
{'_id': 9, 'name': 'Tote bag', 'price': 18, 'colors': ['red', 'blue']}

Your task: the client and db are already set up. Find the product named Mug and print it, then print its stock count and its tags. Insert a Tote bag with _id 9, price 18 and the colors red and blue, print how many products there are now, and find the Tote bag and print it.


Assignment
Follow the Coding Tutorial to read the Mug document, add a Tote bag of its own shape and count the products.


Hint
The count sits inside the Mug's stock dict: open mug["stock"] first, then read ["count"] from it. The Tote bag needs no category or stock: a document holds only the fields you give it.


STEP 1 OF 6
    Ctrl + Enter to check

    Mongo Documents in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free