Python & Data Science

Sql Vs Nosql For Data Science A Decision Reference

You just inherited a project. The backend team chose MongoDB, and you’re staring at a screen full of nested JSON, trying to answer a question that would have taken you thirty seconds in SQL: “Which users who bought product X also viewed product Y?” You can’t just write a JOIN. You’re frustrated. You’ve heard the term “NoSQL” tossed around, and now you’re wondering: Do I need to learn this to be a real data scientist?

The short answer is no. You don’t need to learn NoSQL to be a real data scientist. But understanding when each model fits—and why—will make you dramatically more effective. It will save you from those late-night data-wrangling marathons and help you have smarter conversations with your engineering team.

This article is not a cage match. We aren’t going to declare a winner. Instead, we’re going to build a mental model—a decision-making tool—that you can use every time you face this choice. We’ll use one running example, a startup’s product analytics system, to test both approaches. Think of this as your field guide, not a rulebook.

The Core Mental Model: It’s About the Shape of Your Data, Not the Brand

Before we name any technologies, let’s look at the data itself. Forget databases for a minute. Think about how information naturally organizes itself.

Imagine you’re building an e-commerce system. You have users, orders, and products. How would you store that information on paper? You might have one spreadsheet for users, one for products, and one for orders. The orders sheet wouldn’t contain a user’s full address—it would just have a user_id column that lets you look up the address in the users sheet. This is the relational model. Data is split into strict, separate tables to avoid duplication. To get the full picture, you have to link the tables together.

Now imagine a different approach. You have a folder for each user. Inside that folder is a single document that contains their profile, their last ten orders (with product details), and their site preferences—all in one place. You don’t need to look anything up. This is the document model. Data is stored as self-contained, nested records.

This is the hardest part: neither shape is “better.” They optimize for different access patterns. In plain English, the question is: Do you usually need to ask, “What user placed this order?” (relational) or “Show me everything about this user right now” (document)?

Let’s make this concrete. Here’s the exact same e-commerce data represented in both shapes.

# This is a self-contained code block. It defines all the data it uses.
import json

# ==========================================
# RELATIONAL MODEL: Data normalized into separate tables
# ==========================================
users_table = [
    {"user_id": 1, "name": "Alice", "email": "alice@example.com"},
    {"user_id": 2, "name": "Bob", "email": "bob@example.com"}
]

products_table = [
    {"product_id": 101, "name": "Fancy Keyboard", "price": 120.00},
    {"product_id": 102, "name": "Ergonomic Mouse", "price": 75.00}
]

orders_table = [
    {"order_id": 1001, "user_id": 1, "product_id": 101, "quantity": 1},
    {"order_id": 1002, "user_id": 1, "product_id": 102, "quantity": 2},
    {"order_id": 1003, "user_id": 2, "product_id": 101, "quantity": 1}
]

print("Relational Model:")
print("Users:", users_table)
print("Products:", products_table)
print("Orders:", orders_table)
# Notice: To find out what Alice bought, you need to find her user_id (1),
# filter the orders_table for user_id=1, then match those product_ids
# (101, 102) back to the products_table. That's a JOIN in SQL.

# ==========================================
# DOCUMENT MODEL: Data nested into self-contained user documents
# ==========================================
users_documents = [
    {
        "user_id": 1,
        "name": "Alice",
        "email": "alice@example.com",
        "orders": [
            {
                "order_id": 1001,
                "product": {"product_id": 101, "name": "Fancy Keyboard", "price": 120.00},
                "quantity": 1
            },
            {
                "order_id": 1002,
                "product": {"product_id": 102, "name": "Ergonomic Mouse", "price": 75.00},
                "quantity": 2
            }
        ]
    },
    {
        "user_id": 2,
        "name": "Bob",
        "email": "bob@example.com",
        "orders": [
            {
                "order_id": 1003,
                "product": {"product_id": 101, "name": "Fancy Keyboard", "price": 120.00},
                "quantity": 1
            }
        ]
    }
]

print("\nDocument Model:")
print(json.dumps(users_documents, indent=2))
# Notice: To find out what Alice bought, you just look at Alice's document.
# Everything is right there. But notice the duplication: the Fancy Keyboard
# details appear in both Alice's and Bob's documents. If we change the price,
# we have to update it in multiple places.

In the relational model, Alice’s orders are scattered across the orders_table and products_table. You have to piece them together. The benefit? The product’s price lives in exactly one place. Change it once, and every order that references it sees the new price.

In the document model, everything about Alice is in one tidy package. The benefit? A single read gives you her entire history. The cost? The keyboard’s price is duplicated in Alice’s document and Bob’s document. If you need to update it, you have to hunt down every copy.

This trade-off—between normalization (one source of truth, but you need JOINs) and denormalization (fast reads, but data duplication)—is the fundamental tension. Every decision from here on out is a variation on this theme.

Meet the Contenders: SQL (PostgreSQL) and NoSQL (MongoDB) in Plain English

Now we can name names. When people say “SQL database,” they’re often thinking of PostgreSQL. It’s the gold standard for relational databases: battle-tested, open-source, and packed with features. When people say “NoSQL document database,” they’re often thinking of MongoDB. It’s the most popular document store, designed from the ground up for the JSON-like document model we just saw.

What does each one actually do under the hood?

PostgreSQL stores data in strictly-typed tables. You define the schema upfront: the users table has a name column that holds text, an email column that holds text, and so on. It guarantees ACID (Atomicity, Consistency, Isolation, Durability). Think of this as “bank transaction correctness.” If you transfer money between two accounts, the database ensures both the withdrawal and the deposit happen, or neither does. No half-finished transactions. PostgreSQL has been doing this reliably for over two decades.

MongoDB stores data in flexible “collections” of JSON-like documents. You don’t have to declare a schema ahead of time. One user document can have a phone_number field; the next one might not. MongoDB was designed from the ground up to spread across many servers—what’s called horizontal scaling. If your data grows too big for one machine, you add more machines to the cluster.

Here’s the crucial part: both databases can do things the other is “known for.” PostgreSQL has a feature called JSONB that lets you store and query document-style data inside a relational table. MongoDB has $lookup, which lets you do JOIN-like operations across collections. This is why the debate is often a false dichotomy. The line is blurry.

Let’s see the simplest possible “create and insert” in both systems. Watch how the schema is handled.

# This code block is fully self-contained. It imports its own drivers and connects to local databases.
# IMPORTANT: To run this, you need a local PostgreSQL and MongoDB instance.
# The code assumes default ports and no authentication for demo purposes.

import psycopg2
from pymongo import MongoClient

# ==========================================
# POSTGRESQL: Schema is defined upfront
# ==========================================
# Connect to a local Postgres instance (default database 'postgres')
try:
    pg_conn = psycopg2.connect(
        dbname="postgres",
        user="postgres",
        password="postgres",
        host="localhost",
        port="5432"
    )
    pg_conn.autocommit = True
    pg_cur = pg_conn.cursor()

    # Create a table: we MUST declare the columns and their types.
    pg_cur.execute("""
        CREATE TABLE IF NOT EXISTS users (
            user_id SERIAL PRIMARY KEY,
            name TEXT NOT NULL,
            email TEXT UNIQUE NOT NULL
        );
    """)
    print("PostgreSQL: Table 'users' created with strict schema.")

    # Insert a row. The values must match the declared types.
    pg_cur.execute(
        "INSERT INTO users (name, email) VALUES (%s, %s)",
        ("Alice", "alice@example.com")
    )
    print("PostgreSQL: Inserted a row into 'users'.")

    # Clean up
    pg_cur.execute("DROP TABLE IF EXISTS users;")
    pg_cur.close()
    pg_conn.close()
except Exception as e:
    print(f"PostgreSQL connection/operation failed (this is expected if you don't have it running): {e}")

# ==========================================
# MONGODB: No upfront schema
# ==========================================
try:
    mongo_client = MongoClient("mongodb://localhost:27017/")
    mongo_db = mongo_client["test_database"]
    mongo_collection = mongo_db["users"]

    # Insert a document. No schema declaration needed.
    # The document is just a Python dictionary.
    mongo_collection.insert_one({
        "name": "Alice",
        "email": "alice@example.com"
    })
    print("MongoDB: Inserted a document into 'users' collection. No schema required.")

    # Clean up
    mongo_collection.drop()
    mongo_client.close()
except Exception as e:
    print(f"MongoDB connection/operation failed (this is expected if you don't have it running): {e}")

In PostgreSQL, the CREATE TABLE statement is a contract. You promised that every row in users will have a name (text) and an email (text, and unique). The database will enforce that contract for you, forever.

In MongoDB, the insert_one just… works. The document is a dictionary. There’s no contract. This feels liberating, and it is—but it also means the responsibility for data quality shifts from the database to your application code.

Decision Axis 1: Schema Stability — Will Your Data Shape Change Tomorrow?

Let’s return to our startup. You’re building a product analytics system. Early on, you’re tracking user events: clicks, page views, feature usage. But the product is evolving fast. Next week, you might add a new event type with ten new properties you haven’t even thought of yet. Your data’s shape is a moving target.

This is a classic schema-volatility problem. How does each database handle a change?

In PostgreSQL, you write a migration. You use an ALTER TABLE statement to add a new column. This is a deliberate, controlled process. You can set a default value for existing rows. You can even do it without locking the table (with CONCURRENTLY). It’s safe, but it’s a process. It’s not something you want to do ten times a day during exploratory analysis.

In MongoDB, you just start writing documents with the new field. No migration needed. The database doesn’t care that some documents have a new_feature_flag and others don’t. This speed is a genuine superpower when you’re in the messy, exploratory phase of a project.

Here’s the catch: that flexibility comes at a cost. When you query the data later, you can’t assume a field exists. Your analysis code has to handle missing keys, unexpected types, and the general chaos of a schema that evolved organically.

Let’s see this in action. We’ll try to insert a record with a new, unexpected field into both systems.

# This code block is fully self-contained.
import psycopg2
from pymongo import MongoClient

# ==========================================
# POSTGRESQL: Strict schema rejects the new field
# ==========================================
try:
    pg_conn = psycopg2.connect(
        dbname="postgres", user="postgres", password="postgres",
        host="localhost", port="5432"
    )
    pg_conn.autocommit = True
    pg_cur = pg_conn.cursor()

    # Create a table with only two columns
    pg_cur.execute("""
        CREATE TABLE IF NOT EXISTS events (
            event_id SERIAL PRIMARY KEY,
            event_type TEXT NOT NULL
        );
    """)

    # Try to insert a row with an extra 'new_field' that doesn't exist in the table
    try:
        pg_cur.execute(
            "INSERT INTO events (event_type, new_field) VALUES (%s, %s)",
            ("page_view", "unexpected_value")
        )
    except Exception as e:
        print(f"PostgreSQL INSERT error: {e}")
        print("Interpretation: PostgreSQL rejected the insert because 'new_field' is not a column in the 'events' table.")
        print("The schema is enforced. You cannot accidentally add a field.")

    pg_cur.execute("DROP TABLE IF EXISTS events;")
    pg_cur.close()
    pg_conn.close()
except Exception as e:
    print(f"PostgreSQL connection failed: {e}")

# ==========================================
# MONGODB: Flexible schema accepts the new field silently
# ==========================================
try:
    mongo_client = MongoClient("mongodb://localhost:27017/")
    mongo_db = mongo_client["test_database"]
    mongo_collection = mongo_db["events"]

    # Insert a document with a field we haven't "declared" anywhere
    mongo_collection.insert_one({
        "event_type": "page_view",
        "new_field": "unexpected_value"  # This field is brand new
    })
    print("MongoDB: Insert succeeded. The document now has a 'new_field'.")

    # Now let's query. We have to handle the case where 'new_field' might be missing.
    # Imagine we're doing an analysis and we want to count events with 'new_field'.
    # We can't just assume it exists.
    sample_doc = mongo_collection.find_one()
    # Safely get the field with a default
    new_field_value = sample_doc.get("new_field", "MISSING")
    print(f"MongoDB: Retrieved document. 'new_field' value: {new_field_value}")
    print("Interpretation: MongoDB accepted the new field without complaint.")
    print("But our analysis code must use .get() with a default to handle documents that don't have it yet.")

    mongo_collection.drop()
    mongo_client.close()
except Exception as e:
    print(f"MongoDB connection failed: {e}")

What does this mean for you, the data scientist? If you’re in the exploratory phase, constantly adding new tracking parameters to understand user behavior, MongoDB’s flexibility lets you move at the speed of your curiosity. You don’t have to file a ticket with the DBA every time you want to capture a new data point.

But if you’re building a core business dashboard—one that will be used to make revenue decisions for the next three years—PostgreSQL’s strictness is a feature, not a bug. That error message you saw is the database protecting you from a future where half your events rows have a new_field and half don’t, and your GROUP BY query returns baffling results.

Decision Axis 2: Relationship Integrity — How Much Do You Trust Your Data’s Connections?

Now let’s think about the relationships between our data. In our startup’s system, an order must belong to a valid user and a valid product. What happens if someone—or a buggy script—tries to insert an order that references a user who doesn’t exist?

This is about referential integrity. It’s the database’s promise that the connections in your data are real.

PostgreSQL makes this a core feature. You define a foreign key constraint: the user_id in the orders table must match an actual user_id in the users table. You can even tell the database what to do if someone tries to delete a user who has orders: ON DELETE CASCADE (delete the orders too) or ON DELETE RESTRICT (block the deletion). The database enforces this at the engine level. It’s part of the “C” (Consistency) in ACID.

MongoDB, by default, has no server-enforced foreign keys. You can model relationships using embedded documents (putting the order inside the user document) or by storing manual references (an order document with a user_id field). But the application code is solely responsible for keeping those references valid. MongoDB’s own comparison page states this trade-off clearly: non-relational databases trade “strong cross-entity integrity guarantees” for flexibility and scale.

What does this mean for a data scientist? If you’re doing revenue reporting, a missing product reference in an order row is a nightmare. That order’s value can’t be attributed to a product category. Your revenue numbers are suddenly wrong, and you have to spend your morning hunting down orphaned records. You want the database to prevent that from ever happening.

If you’re storing semi-structured log data—say, user clickstream events where a broken session ID is a minor annoyance that affects 0.01% of your data—the trade-off is absolutely worth it.

Let’s see the difference in practice.

# This code block is fully self-contained.
import psycopg2
from pymongo import MongoClient

# ==========================================
# POSTGRESQL: Foreign key constraint prevents orphaned records
# ==========================================
try:
    pg_conn = psycopg2.connect(
        dbname="postgres", user="postgres", password="postgres",
        host="localhost", port="5432"
    )
    pg_conn.autocommit = True
    pg_cur = pg_conn.cursor()

    # Create parent table
    pg_cur.execute("""
        CREATE TABLE IF NOT EXISTS users (
            user_id SERIAL PRIMARY KEY,
            name TEXT NOT NULL
        );
    """)

    # Create child table with a foreign key constraint
    pg_cur.execute("""
        CREATE TABLE IF NOT EXISTS orders (
            order_id SERIAL PRIMARY KEY,
            user_id INTEGER REFERENCES users(user_id) ON DELETE RESTRICT,
            amount NUMERIC
        );
    """)

    # Try to insert an order with a user_id that doesn't exist (999)
    try:
        pg_cur.execute(
            "INSERT INTO orders (user_id, amount) VALUES (%s, %s)",
            (999, 50.00)
        )
    except Exception as e:
        print(f"PostgreSQL INSERT error: {e}")
        print("Interpretation: PostgreSQL blocked the insert because user_id 999 does not exist in the 'users' table.")
        print("The database guarantees that every order references a real user.")

    pg_cur.execute("DROP TABLE IF EXISTS orders;")
    pg_cur.execute("DROP TABLE IF EXISTS users;")
    pg_cur.close()
    pg_conn.close()
except Exception as e:
    print(f"PostgreSQL connection failed: {e}")

# ==========================================
# MONGODB: No foreign key constraint. The insert succeeds.
# ==========================================
try:
    mongo_client = MongoClient("mongodb://localhost:27017/")
    mongo_db = mongo_client["test_database"]
    orders_col = mongo_db["orders"]

    # Insert an order referencing a non-existent user
    orders_col.insert_one({
        "order_id": 1,
        "user_id": 999,  # This user doesn't exist
        "amount": 50.00
    })
    print("MongoDB: Insert succeeded. The order references a non-existent user.")

    # Now, let's simulate an analysis that tries to join orders with users.
    # We'll use MongoDB's $lookup (its version of a JOIN).
    # First, insert a real user so we can see the difference.
    users_col = mongo_db["users"]
    users_col.insert_one({"user_id": 1, "name": "Alice"})

    # Aggregation pipeline: join orders to users
    pipeline = [
        {
            "$lookup": {
                "from": "users",
                "localField": "user_id",
                "foreignField": "user_id",
                "as": "user_info"
            }
        },
        {
            "$addFields": {
                # If the lookup found no matching user, the array is empty.
                # We have to manually flag broken references.
                "is_orphaned": {"$eq": [{"$size": "$user_info"}, 0]}
            }
        }
    ]

    results = list(orders_col.aggregate(pipeline))
    for doc in results:
        status = "ORPHANED (no matching user)" if doc["is_orphaned"] else "Valid"
        print(f"Order {doc['order_id']}: {status}")

    print("Interpretation: MongoDB allowed the orphaned order.")
    print("Our analysis pipeline had to explicitly check for broken references with $lookup and $addFields.")
    print("This adds complexity to every analytical query that relies on relationships.")

    orders_col.drop()
    users_col.drop()
    mongo_client.close()
except Exception as e:
    print(f"MongoDB connection failed: {e}")

Look at the MongoDB pipeline. We had to write a $lookup (which is more complex than a SQL JOIN) and then add a manual step ($addFields) just to check if the relationship was broken. In PostgreSQL, the database simply refused to let the bad data in. That’s one less thing your analysis code has to worry about.

The False Dichotomy: When One Database Can Do Both Jobs

By now, you might feel like you have to pick a side. You don’t. The real world is messier and more interesting. Both PostgreSQL and MongoDB have stretched into each other’s territory, and the smartest teams often use a single database to handle multiple data shapes.

Let’s start with PostgreSQL’s secret weapon: JSONB. You can have a strictly-typed users table with columns like user_id, signup_date, and email. But you can also add a preferences column of type JSONB. This column stores flexible, nested, document-style data. You get relational integrity for the core data and document flexibility for the messy parts—in one database.

MongoDB’s countermove is $lookup, which we just used. It lets you perform JOIN-like operations across collections. MongoDB’s own documentation is quick to point out that NoSQL databases can store relationship data—they just store it differently. The JOINs aren’t as performant as PostgreSQL’s indexed foreign key JOINs, but they exist.

The real-world pattern many data teams use is this: PostgreSQL is the primary source of truth for core business entities (users, orders, products). For the flexible, rapidly-changing parts—like user preferences, feature flags, or raw event payloads—they either pipe that data into a separate MongoDB instance or, more simply, just use PostgreSQL’s JSONB columns.

Think of it this way: you’re not choosing a religion. You’re choosing the right tool for each data shape in your system. Sometimes that’s two tools. Often, it’s one tool that’s good at both.

Let’s see PostgreSQL’s JSONB in action. We’ll create a table with structured columns and a flexible JSONB blob, then query both seamlessly.

# This code block is fully self-contained.
import psycopg2
import json

try:
    pg_conn = psycopg2.connect(
        dbname="postgres", user="postgres", password="postgres",
        host="localhost", port="5432"
    )
    pg_conn.autocommit = True
    pg_cur = pg_conn.cursor()

    # Create a table with a structured column AND a flexible JSONB column
    pg_cur.execute("""
        CREATE TABLE IF NOT EXISTS users_hybrid (
            user_id SERIAL PRIMARY KEY,
            signup_date DATE NOT NULL,
            preferences JSONB
        );
    """)

    # Insert a row. The 'preferences' column takes a JSON string.
    pg_cur.execute(
        "INSERT INTO users_hybrid (signup_date, preferences) VALUES (%s, %s)",
        ("2024-01-15", json.dumps({"theme": "dark", "notifications": {"email": True, "push": False}}))
    )

    # Now, query the data. We can use standard SQL on the structured column...
    # AND use JSONB operators to extract specific keys from the flexible blob.
    pg_cur.execute("""
        SELECT
            user_id,
            signup_date,
            preferences ->> 'theme' AS theme,
            preferences -> 'notifications' ->> 'push' AS push_enabled
        FROM users_hybrid
        WHERE signup_date > '2024-01-01'
    """)

    row = pg_cur.fetchone()
    print(f"PostgreSQL Hybrid Query Result:")
    print(f"User ID: {row[0]}")
    print(f"Signup Date: {row[1]}")
    print(f"Theme (from JSONB): {row[2]}")
    print(f"Push Enabled (from nested JSONB): {row[3]}")
    print("Interpretation: We queried structured data (signup_date) and flexible JSON data (preferences) in one SQL statement.")
    print("PostgreSQL's JSONB gives us the best of both worlds.")

    pg_cur.execute("DROP TABLE IF EXISTS users_hybrid;")
    pg_cur.close()
    pg_conn.close()
except Exception as e:
    print(f"PostgreSQL connection failed: {e}")

This is powerful. You can have a rigid, reliable schema for the data that runs your business, and a flexible, squishy JSON blob for the data that’s still being figured out. You don’t need to introduce a second database to get document flexibility.

The Scaling Story: What “Web Scale” Actually Means for a Data Scientist

You’ve probably heard that NoSQL databases are for “web scale” and SQL databases can’t handle big data. This is the most misunderstood part of the entire discussion. Let’s demystify it.

There are two ways to scale a database. Vertical scaling means getting a bigger server: more RAM, faster CPUs, bigger SSDs. This is PostgreSQL’s default path. And it works shockingly well. Modern cloud instances can handle terabytes of data and thousands of queries per second on a single machine.

Horizontal scaling means spreading your data across many cheaper servers, or shards. This is MongoDB’s design sweet spot. When your write load is so massive that a single server’s disk can’t keep up—think IoT sensor data from millions of devices, or a social media firehose—you need to distribute the writes. MongoDB’s sharding makes this relatively turnkey.

What does this actually mean for you, the data scientist? For the vast majority of analytical work, the answer is: not much. Your queries are likely running on a data warehouse (like BigQuery or Snowflake) or a read replica of the production database, not the production primary. If your analytical queries on a PostgreSQL replica are slow, the solution is often a bigger read replica, not a migration to NoSQL. If the engineering team chose MongoDB for the production system, it’s almost certainly because they needed to handle a firehose of writes, not because they hate SQL.

Let’s check this against the data. We’ll run a simple timing experiment. We’ll insert one million records into a local PostgreSQL instance and a local MongoDB instance, then run a simple aggregation. The point isn’t to declare a speed winner—it’s to show that for typical analytical queries on a single node, both are fast enough. The scaling concern is an operational one, not an analytical one.

# This code block is fully self-contained. It generates its own data.
import time
import random
import psycopg2
from pymongo import MongoClient

NUM_RECORDS = 100000  # Reduced to 100k for a quicker demo; the principle holds.

# ==========================================
# POSTGRESQL: Insert and aggregate
# ==========================================
try:
    pg_conn = psycopg2.connect(
        dbname="postgres", user="postgres", password="postgres",
        host="localhost", port="5432"
    )
    pg_conn.autocommit = True
    pg_cur = pg_conn.cursor()

    pg_cur.execute("""
        CREATE TABLE IF NOT EXISTS scale_test (
            id SERIAL PRIMARY KEY,
            value INTEGER
        );
    """)

    # Insert records
    print(f"PostgreSQL: Inserting {NUM_RECORDS} records...")
    start = time.time()
    for _ in range(NUM_RECORDS):
        pg_cur.execute("INSERT INTO scale_test (value) VALUES (%s)", (random.randint(1, 100),))
    insert_time_pg = time.time() - start
    print(f"PostgreSQL insert time: {insert_time_pg:.2f} seconds")

    # Run an aggregation
    start = time.time()
    pg_cur.execute("SELECT AVG(value) FROM scale_test")
    avg_result = pg_cur.fetchone()[0]
    query_time_pg = time.time() - start
    print(f"PostgreSQL AVG query time: {query_time_pg:.4f} seconds. Result: {avg_result:.2f}")

    pg_cur.execute("DROP TABLE IF EXISTS scale_test;")
    pg_cur.close()
    pg_conn.close()
except Exception as e:
    print(f"PostgreSQL connection failed: {e}")

# ==========================================
# MONGODB: Insert and aggregate
# ==========================================
try:
    mongo_client = MongoClient("mongodb://localhost:27017/")
    mongo_db = mongo_client["test_database"]
    mongo_col = mongo_db["scale_test"]

    print(f"\nMongoDB: Inserting {NUM_RECORDS} documents...")
    start = time.time()
    docs = [{"value": random.randint(1, 100)} for _ in range(NUM_RECORDS)]
    mongo_col.insert_many(docs)
    insert_time_mongo = time.time() - start
    print(f"MongoDB insert time: {insert_time_mongo:.2f} seconds")

    # Run an aggregation
    start = time.time()
    pipeline = [
        {"$group": {"_id": None, "avg_value": {"$avg": "$value"}}}
    ]
    agg_result = list(mongo_col.aggregate(pipeline))
    avg_result_mongo = agg_result[0]["avg_value"]
    query_time_mongo = time.time() - start
    print(f"MongoDB AVG query time: {query_time_mongo:.4f} seconds. Result: {avg_result_mongo:.2f}")

    mongo_col.drop()
    mongo_client.close()
except Exception as e:
    print(f"MongoDB connection failed: {e}")

print("\nInterpretation: On a single node with a moderate dataset, both databases return sub-second aggregation results.")
print("The scaling concern is about handling millions of writes per second across many servers—an operational challenge, not an analytical one.")

For the analytical queries you’re likely writing—GROUP BY, AVG, COUNT—both databases will return results in a blink on a modern machine. The real scaling pressure is on the write side, and that’s the engineering team’s domain. Your job is to understand why they made the choice they did, so you can work with it effectively.

The Data Scientist’s Workflow: Querying, Analyzing, and Modeling

Let’s bring this all the way home to your daily life. You’re not a database administrator. You’re pulling data into a pandas DataFrame for analysis and scikit-learn for modeling. How does the database choice actually affect your Python code?

From PostgreSQL, you write a SQL query. You get back a clean, rectangular result set—rows and columns. It drops directly into a pandas DataFrame. The column types are predictable: integers are integers, dates are dates. This is the workflow you already know.

From MongoDB, you write a JSON-like query or an aggregation pipeline. You get back a list of nested dictionaries. Before you can do anything useful in pandas or scikit-learn, you have to flatten that nested structure into a rectangular table. This is the hidden cost of MongoDB’s flexibility: your analysis code has to do more data cleaning.

But wait—what if you’re doing NLP on unstructured text stored in a JSON document? MongoDB’s document model might actually be a better fit for the raw data before you vectorize it. The question isn’t “which database is better?” It’s “does the database’s data model match my analytical data model?”

Let’s walk through a complete, side-by-side mini-workflow. We’ll query both databases, load the data into pandas, and train a simple linear regression. Watch the extra steps on the MongoDB side.

# This code block is fully self-contained. It generates its own synthetic data.
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import psycopg2
from pymongo import MongoClient

# ==========================================
# STEP 0: Generate synthetic data for both databases
# ==========================================
np.random.seed(42)
n_samples = 1000
X1 = np.random.randn(n_samples)
X2 = np.random.randn(n_samples)
y = 3.0 * X1 + 1.5 * X2 + np.random.randn(n_samples) * 0.5

# ==========================================
# POSTGRESQL WORKFLOW
# ==========================================
try:
    pg_conn = psycopg2.connect(
        dbname="postgres", user="postgres", password="postgres",
        host="localhost", port="5432"
    )
    pg_conn.autocommit = True
    pg_cur = pg_conn.cursor()

    pg_cur.execute("""
        CREATE TABLE IF NOT EXISTS model_data (
            id SERIAL PRIMARY KEY,
            feature_1 DOUBLE PRECISION,
            feature_2 DOUBLE PRECISION,
            target DOUBLE PRECISION
        );
    """)

    for i in range(n_samples):
        pg_cur.execute(
            "INSERT INTO model_data (feature_1, feature_2, target) VALUES (%s, %s, %s)",
            (X1[i], X2[i], y[i])
        )

    # Query: A clean, rectangular result set
    pg_cur.execute("SELECT feature_1, feature_2, target FROM model_data")
    pg_data = pg_cur.fetchall()
    pg_columns = [desc[0] for desc in pg_cur.description]

    # Load directly into pandas
    df_pg = pd.DataFrame(pg_data, columns=pg_columns)
    print("PostgreSQL: Data loaded into DataFrame. Shape:", df_pg.shape)
    print("PostgreSQL: dtypes are predictable:")
    print(df_pg.dtypes)

    # Train model
    model_pg = LinearRegression()
    model_pg.fit(df_pg[["feature_1", "feature_2"]], df_pg["target"])
    print(f"PostgreSQL Model Coefficients: {model_pg.coef_}")

    pg_cur.execute("DROP TABLE IF EXISTS model_data;")
    pg_cur.close()
    pg_conn.close()
except Exception as e:
    print(f"PostgreSQL workflow failed: {e}")

# ==========================================
# MONGODB WORKFLOW
# ==========================================
try:
    mongo_client = MongoClient("mongodb://localhost:27017/")
    mongo_db = mongo_client["test_database"]
    mongo_col = mongo_db["model_data"]

    # Insert nested documents to simulate a realistic MongoDB schema
    docs = []
    for i in range(n_samples):
        docs.append({
            "features": {
                "feature_1": X1[i],
                "feature_2": X2[i]
            },
            "target": y[i]
        })
    mongo_col.insert_many(docs)

    # Query: Get all documents
    mongo_data = list(mongo_col.find({}, {"_id": 0}))

    # Flatten the nested structure into a rectangular format
    # THIS IS THE EXTRA STEP.
    flattened_data = []
    for doc in mongo_data:
        flattened_data.append({
            "feature_1": doc["features"]["feature_1"],
            "feature_2": doc["features"]["feature_2"],
            "target": doc["target"]
        })

    df_mongo = pd.DataFrame(flattened_data)
    print("\nMongoDB: Data loaded and flattened into DataFrame. Shape:", df_mongo.shape)
    print("MongoDB: We had to manually extract nested fields to get a clean table.")

    # Train the same model
    model_mongo = LinearRegression()
    model_mongo.fit(df_mongo[["feature_1", "feature_2"]], df_mongo["target"])
    print(f"MongoDB Model Coefficients: {model_mongo.coef_}")

    mongo_col.drop()
    mongo_client.close()
except Exception as e:
    print(f"MongoDB workflow failed: {e}")

print("\nInterpretation: Both workflows trained the same model. But the MongoDB path required an explicit flattening step.")
print("If your MongoDB data is deeply nested, this step can become the most time-consuming part of your analysis.")
print("The rigidity of PostgreSQL's schema means the database already enforced a structure, so your DataFrame's dtypes are predictable.")

The PostgreSQL path is a straight line: query, DataFrame, model. The MongoDB path has a detour: query, flatten, DataFrame, model. If your data is deeply nested—think user documents containing arrays of orders, each containing arrays of items—that flattening step can become a significant Python script in its own right. This is the hidden tax of schema flexibility. You pay it at analysis time, not at insert time.

The Decision Reference: A Plain-English Checklist

We’ve covered a lot of ground. Let’s synthesize everything into a practical, non-dogmatic checklist. When you’re facing a database decision—or just trying to understand a decision that was already made—ask these five questions.

QuestionIf Yes…If No…
1. Is the data’s structure stable and well-understood?Lean toward SQL. A fixed schema is a contract that keeps your data clean.Lean toward NoSQL. If you’re adding new fields weekly, you need the flexibility.
2. Do you need ironclad guarantees that Order #12345’s user actually exists?SQL. Foreign key constraints are non-negotiable for financial or core business data.NoSQL is fine. If a broken reference is a minor annoyance (like in log data), the trade-off is worth it.
3. Are you primarily reading data for analytics, or handling a massive firehose of writes?SQL is great for read-heavy analytical workloads.NoSQL’s horizontal scaling helps when the write volume is the primary bottleneck.
4. Can you get away with using just one database?PostgreSQL with JSONB might be your answer. It gives you relational integrity and document flexibility in one system. Don’t introduce a second database unless you have to.If you genuinely need both a rock-solid relational core and a massively scalable document store for a separate high-write stream, a polyglot approach is justified.
5. What does your team already know?A “worse” database that your team understands deeply is better than a “better” one they’ll misuse. Operational familiarity often trumps technical elegance.If the team is excited to learn and the use case is a clear fit, it’s worth the learning curve.

This checklist isn’t a flowchart that spits out a definitive answer. It’s a set of questions that focus the conversation on what actually matters: the shape of your data, the integrity of your relationships, and the realities of your team.

Recap and What’s Next

You came in wondering if you needed to learn NoSQL to be a “real” data scientist. You’re leaving with something more valuable: a mental model for making a practical decision.

  • You learned the two core data shapes: tabular/relational (normalized tables, JOINs, one source of truth) and nested/document (self-contained records, fast reads, potential duplication).
  • You saw how PostgreSQL and MongoDB embody those shapes, and—crucially—how each can stretch into the other’s territory with JSONB and $lookup.
  • You now have a checklist based on schema stability, relationship integrity, scaling needs, and team familiarity—not brand loyalty.

This was never a debate. It’s a decision. And you now have the tools to make it.

Next in this series, we’ll stop comparing and start building. We’ll take one of these databases and construct a real analytics pipeline, from raw data to a trained model, end-to-end. You’ll see the full workflow in action.

Check Your Understanding

  1. Remember: What does the acronym ACID stand for, and which database model is it most strongly associated with?
  2. Understand: In your own words, explain the trade-off between normalization and denormalization. Why might you choose one over the other for a product catalog vs. a user activity log?
  3. Apply: You’re building a prototype for a new feature that tracks user clicks on a redesigned interface. The exact properties of each click event are likely to change daily as you iterate. Which database’s default behavior (strict schema vs. schema-less) would let you move faster during this phase, and why?
  4. Analyze: A colleague argues, “We should use MongoDB for everything because it scales horizontally and SQL databases can’t handle big data.” Based on what you’ve read, identify two flaws or oversimplifications in this statement.
  5. Evaluate: Consider a system that manages hospital patient records (diagnoses, medications, allergies) and also stores high-volume, semi-structured data from wearable fitness trackers. Propose a database architecture (single database or polyglot) and justify your choice using at least two concepts from the article (e.g., schema stability, relationship integrity, JSONB, polyglot persistence).
  6. Create: Design a simple data model for a content publishing platform (authors, articles, comments). First, sketch it as a set of normalized relational tables. Then, sketch it as a set of MongoDB documents. Write a brief paragraph explaining which access pattern—“show me all comments on this article” vs. “show me this author’s full profile and recent articles”—is better served by each model.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • SQL & Data Engineering Under review

    SQL Window Functions You Actually Need for Data Science

    Master SQL window functions for data science: running totals, RANK, LAG, NTILE, and the common pitfalls that trip up candidates in technical interviews.

  • SQL & Data Engineering Under review

    Sql Join Types Reference With Diagrams That Actual

    Here's the Venn diagram you've probably seen a thousand times. Two circles overlapping. The shaded intersection is the INNER JOIN. The left circle plus the intersection is the LEFT JOIN. Simple, right?

  • SQL & Data Engineering Under review

    BigQuery ML: Training Models Without Leaving SQL

    You've been there. You have a massive table in BigQuery — millions of rows, terabytes of data — and you want to train a simple logistic regression.

  • SQL & Data Engineering Under review

    Common SQL Join Mistakes That Quietly Duplicate Your Rows

    Learn the four most common SQL join mistakes that silently duplicate your rows, how to spot them with a 30-second diagnostic, and the right fix for each one.

Looking for something else?

Search every article by title, summary or topic.