Start learning free

LESSON 57 OF 66 · NOSQL: MONGODB

Indexes and Unique Fields in Python

Practice

With no index, a find reads every document of the collection and checks each one: a full scan. An index on a field keeps that field's values in sorted order, each pointing to its document, like the index at the back of a book. A find on an indexed field goes straight to its matches, which matters once a collection holds millions of documents.

create_index("field") builds an index and gives back its name: the field, then 1 for ascending. index_information() gives back a dict with one key per index; every collection already has _id_, the index on _id.

With unique=True, the index also refuses a second document with a value it already holds, like SQL's UNIQUE. insert_one then raises DuplicateKeyError, from pymongo.errors, and a try/except catches it so the program goes on. On the products' names, it would look like this:

db.products.create_index("name", unique=True)
try:
    db.products.insert_one({"name": "Mug", "price": 1})
except DuplicateKeyError:
    print("there is a Mug already")

Ana Pop already uses ana@example.com. Your finished script prints the lines below. The last one comes from a line the lesson runs after your code: still 5 customers, so nothing was added.

['_id_', 'email_1']
ana@example.com is already taken
category_1
Customers: 5

The lesson runs on an in-memory MongoDB that already holds the shop; the same code runs unchanged on a real MongoDB server.

Your task: create a unique index on the customers' email and print the sorted names from index_information(). Then, inside a try, insert "Ana Twin" with the email "ana@example.com", and in except DuplicateKeyError print ana@example.com is already taken. Last, print what db.products.create_index("category") gives back.


Assignment
Follow the Coding Tutorial to add a unique index on the customers' email, catch the duplicate insert it refuses, and index the products' category.


Hint
sorted() on a dict gives its keys as a sorted list. The starting code already imports DuplicateKeyError, and except lines up with try:, with the lines inside both indented.


STEP 1 OF 7
    Ctrl + Enter to check

    Mongo Indexes 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