Latticework

Command Palette

Search for a command to run...

MongoDB

Documents & Collections

16 min

Explanation

MongoDB stores documents (JSON-like nested objects) in collections (a loose grouping — analogous to a table, but without a required fixed schema). Two documents in the same collection can have completely different fields — useful for data that genuinely varies in shape, at the cost of the strong guarantees a relational schema gives you (from the Database Design course's constraints).

users = [
    {"name": "Alice", "age": 30, "tags": ["admin"]},
    {"name": "Bob", "age": 25},   # no 'tags' field at all -- and that's fine
]
Try it

matches_query with multiple keys requires ALL of them to match -- this is MongoDB's implicit AND behavior when you pass a query object with several fields, like {'dept': 'eng', 'age': 30}.

Loading editor…
Explanation

Querying a MongoDB collection is conceptually identical to filtering a Python list of dicts — find_documents here is a simplified version of what collection.find({...}) does for real:

def find_documents(collection, query):
    return [doc for doc in collection if matches_query(doc, query)]

engineers = find_documents(users, {"dept": "eng"})
print(engineers)   # both Alice and Carol

Real MongoDB queries support far more than plain equality — operators like $gt (greater than), $in (value in a list), and $regex (pattern matching) — but the underlying idea (a query object describing which documents to keep) is exactly this.

Exercise

Write `matches_query(document, query)`: return True if every key in `query` matches the same key's value in `document` (an empty query matches everything).

Exercise

Using `matches_query` below, write `find_documents(collection, query)`, returning every document in `collection` that matches `query`.

Quiz

In MongoDB's document model, how does a 'document' compare to a row in a relational table?

Checkpoint

You can match a document against a query object and filter a collection, understanding MongoDB's flexible, schema-optional document model.