DEV Community

Cover image for MongoDB vs PostgreSQL: Why the Same Data Looks So Different
VisuaLeaf
VisuaLeaf

Posted on

MongoDB vs PostgreSQL: Why the Same Data Looks So Different

When deciding between MongoDB and PostgreSQL, the biggest difference is how the data is organized.

PostgreSQL is a strong choice when the data is structured and works well in related tables. MongoDB is often more suitable when the data is flexible, nested, or expected to evolve.

Both databases are great, but they approach the same data in different ways.

To make that easier to understand, the same clinic data is shown below in two forms: once as MongoDB documents and once as PostgreSQL tables.

MongoDB document model compared with PostgreSQL relational schema for clinic data

The same clinic data was modeled as a MongoDB document and a PostgreSQL relational schema.

What Makes Them Different: Tables vs Documents

This picture illustrates how the same data about ''clinic visits'' looks in two database systems. In MongoDB, the information about visits is combined within one document, whereas PostgreSQL stores the data in separate tables.

Diagram Detail MongoDB PostgreSQL
Structure Single visits collection Multiple tables
How the data is organized Patient, doctor, symptoms, prescriptions, and invoice are all included in one document Patients, doctors, appointments, prescriptions, and invoices are stored in separate tables
Best for Data that is usually read together Data with strong relationships
Example from the diagram One clinic visit contains nested details One appointment connects to a patient, doctor, prescriptions, and invoice
Main advantage It's easier to read a whole clinic visit in one place Relationships are clear and protected
What to be careful about Documents can become inconsistent or too large without good design Queries often need joins to bring related data together

That is the basic distinction between the two databases.

In MongoDB, we start with the document.

In PostgreSQL, we start with the relationships.

Both database models can represent the same clinic system, but the way you look at your data changes significantly.

SQL vs NoSQL Schema Design: Structure First vs Data First

Another big difference is how the structure is created.

In PostgreSQL, you first create the table. Then you insert the data.

CREATE TABLE lab_results (
    result_id SERIAL PRIMARY KEY,
    patient_name VARCHAR(120) NOT NULL,
    test_name VARCHAR(100) NOT NULL,
    result_value VARCHAR(50) NOT NULL,
    result_status VARCHAR(30) NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

After the structure exists, you can insert rows:

INSERT INTO lab_results (patient_name, test_name, result_value, result_status)
VALUES
('Anna Keller', 'Blood Glucose', '92 mg/dL', 'normal'),
('Matei Ionescu', 'White Blood Cells', '12.1 x10^9/L', 'high');
Enter fullscreen mode Exit fullscreen mode

Then the data appears in a table:

In a visual database GUI, this process becomes easier to follow: first, the table is created, then rows are inserted, and finally, the data appears in table view.

PostgreSQL example showing CREATE TABLE, INSERT INTO, and inserted rows in a table

PostgreSQL requires the table structure before inserting data.

MongoDB works differently. You can insert the document directly:

db.labResults.insertOne({
  patientName: "Anna Keller",
  testName: "Blood Glucose",
  resultValue: "92 mg/dL",
  resultStatus: "normal"
})
Enter fullscreen mode Exit fullscreen mode

And the structure comes from the document you insert.

MongoDB insertMany example showing lab results documents created after inserting data

MongoDB creates the collection and document structure when data is inserted.

In MongoDB, we do not need to create the collection structure first. When we insert the document, MongoDB creates the collection and stores the fields from the document.

So, in simple words:

PostgreSQL: create the structure first, then insert data.

MongoDB: insert the document first, and the structure appears from the data.

If you want more control, MongoDB also lets you add *validation rules* later. We explain this step by step in our article about MongoDB JSON Schema Validation.

Data Querying: SQL JOINs vs Document-Based Querying

The second difference after the storage is in querying.

In PostgreSQL, data is stored in separate tables, which requires us to query using JOIN to combine relevant data.

For instance, if we would like to get clinic visits where both patients' and doctors' names are included, our query will be something like this:

SELECT 
    a.appointment_id,
    p.full_name AS patient_name,
    d.full_name AS doctor_name,
    d.specialization,
    a.appointment_date,
    a.status
FROM appointments a
JOIN patients p ON a.patient_id = p.patient_id
JOIN doctors d ON a.doctor_id = d.doctor_id;
Enter fullscreen mode Exit fullscreen mode

PostgreSQL query in VisuaLeaf joining appointments, patients, and doctors, with combined results displayed in a table.

PostgreSQL JOIN query combining appointments, patients, and doctors.

When using MongoDB, the data is stored close together within the document. Therefore, you would not need to join multiple tables, as the following MongoDB command can be used to obtain the information:

db.visits.find({
  "doctor.specialization": "Cardiology",
  status: "completed"
})
Enter fullscreen mode Exit fullscreen mode

MongoDB query in VisuaLeaf filtering clinic visits by doctor specialization and status, with results shown in Tree View.

MongoDB query result showing a nested clinic visit document.

If you need the entire visit record containing all the required data, it would make sense to choose this approach.

MongoDB can also join data when needed, using stages like $lookup or $graphLookup in the aggregation pipeline, but in many document models, the goal is to store related data together when it is usually read together.

Here are the key differences to remember:

PostgreSQL relies on joins to obtain related data.

MongoDB queries documents containing all the related data.

Transactions and ACID: Saving Changes Safely

A transaction means that several database changes are treated as one safe operation.

Think about a clinic visit. When the visit is finished, the system may need to:

  • mark the visit as completed
  • save the prescription
  • create the invoice

Such operations have something in common. If one operation fails to complete, the whole group of operations should be rolled back, not just a part of them.

The logic of ACID transactions lies right there: *Either all is saved, or nothing is changed at all*.

Transaction in PostgreSQL

As we know, PostgreSQL separates data into different tables. Therefore, a transaction is able to update multiple related tables.

BEGIN;  

UPDATE appointments  
SET status = 'completed'  
WHERE appointment_id = 3;  

INSERT INTO prescriptions (appointment_id, medication_name, dosage, duration_days)  
VALUES (3, 'Skin cream', 'Apply twice daily', 10);  

INSERT INTO invoices (appointment_id, amount, payment_status)  
VALUES (3, 95.00, 'pending');  

COMMIT;  
Enter fullscreen mode Exit fullscreen mode

Here, PostgreSQL updates the appointment, adds the prescription, and creates the invoice as one operation.

You can check the result with a query like this:

PostgreSQL transaction result showing appointment, prescription, and invoice

PostgreSQL transaction result showing appointment, prescription, and invoice.

After the transaction runs, the appointment is marked as completed, the prescription is added, and the invoice is created.

Transaction in MongoDB

In this case, for the database MongoDB, the update is more straightforward since the data is within the same document.

db.visits.updateOne(  
{ visitId: "VIS-1003" },  
{  
$set: {  
status: "completed",  
prescriptions: [  
{  
medicationName: "Skin cream",  
dosage: "Apply twice daily",  
durationDays: 10  
}  
],  
invoice: {  
amount: 95.00,  
paymentStatus: "pending",  
issuedAt: new Date()  
}  
}  
}  
)  
Enter fullscreen mode Exit fullscreen mode

This update is for a one-visit document. The status, prescriptions, and invoices are saved in the same document.

MongoDB update result showing completed visit with prescription and invoice

MongoDB update result showing the visit document updated in one place.

It is possible to have multi-document transactions in MongoDB. However, since the relevant visit information is kept in the same document, one document is enough.

Hence, it is not because only PostgreSQL uses transaction management.

Transaction management is available in both PostgreSQL and MongoDB.

The critical point is that transaction management will be required for PostgreSQL because the data is stored in separate tables, whereas in MongoDB, all relevant data may be put in one document.

Performance: Which One Is Faster?

Many people ask which solution will give them more speed. The answer is not straightforward.

MongoDB is not faster in every case. PostgreSQL is not faster in every case either.

Both solutions can work fast, and both can work slowly.

It depends on the model design, the way you write the queries, and whether the right indexes are present.

To make this more practical, I used the same question in both databases:

Show completed cardiology visits.

  1. In PostgreSQL, the query joins the appointments, patients, and doctors tables to build the result.

PostgreSQL EXPLAIN ANALYZE plan in VisuaLeaf for a clinic query joining appointments, patients, and doctors.

PostgreSQL query plan for finding completed cardiology visits through related tables.

  1. In MongoDB, the result can be read from the visits collection, because the visit details are stored inside the document.

MongoDB query analysis in VisuaLeaf showing index usage for completed cardiology visits.

MongoDB query analysis for finding completed cardiology visits in one collection.

This is not meant to prove that one database is always faster. The example is small, and real performance depends on the amount of data, indexes, schema design, and query patterns.

But it shows the idea clearly: PostgreSQL often builds the answer by connecting tables, while MongoDB can read related data from one document when the model is designed that way.

Instead of asking:

Which solution is faster?

You should ask:

Which database suits the way my app reads and writes data?

That question is more useful.

Scaling: Expanding from 2 TB to 4 TB

When talking about scaling, we discuss how we should help our database support larger volumes, more users, or an increasing number of requests.

One possible analogy may look like this:

What will happen when our database grows from 2 TB to 4 TB?

When it comes to expanding PostgreSQL, most often we start with scaling up. We mean that we make our primary server even stronger by adding more computing power, additional memory, etc. Also, read replicas may be used, but our core database is still built around the single main server.

As far as scaling MongoDB, it is done with scaling out, using the technique called sharding. Here, the data is distributed between different servers.

Let us take, for instance, our visits collection. It may stay the same collection; however, its documents will be spread between several shards. Which shard will store which documents depends on the chosen shard key, e.g., clinicId, region, etc.

PostgreSQL vs MongoDB scaling

PostgreSQL usually scales by making one main server stronger, while MongoDB can scale by spreading one collection across multiple shards.

As you see, the difference lies in:

PostgreSQL grows through expanding the primary database.

MongoDB can scale by distributing its documents across multiple servers.

But it does not mean we should use MongoDB solely because of its scalability.

Some projects will never require any form of sharding. But PostgreSQL is also capable of handling extremely large datasets with proper indexing, partitioning, replicas, and other techniques.

However, the more pertinent question is whether or not:

Do I need one strong relational system, or do I expect my data to be distributed across multiple servers?

For this comparison, I used VisuaLeaf, a GUI tool that works with both NoSQL and SQL databases. It helped me view MongoDB documents and PostgreSQL tables in the same workspace. You can download it here: VisuaLeaf.

Download for Free

Which One Should You Choose?

Go with PostgreSQL if you have structured and relational data, and it relies heavily on rules.

When PostgreSQL is the best choice:

  • use tables with foreign keys
  • apply joins
  • make transactions
  • generate reports
  • have consistency of the data

Use MongoDB if you have flexible and nested data and it is more convenient to work with documents.

When MongoDB is better:

  • use JSON documents
  • have flexible fields
  • have nested structure
  • change the structure fast
  • have data that is used together

Therefore, there is no question about which database management system is better.

You should choose the one that corresponds to how your application works.

Conclusion

MongoDB and PostgreSQL both provide solutions for similar issues but through entirely separate paths.

After building the same clinic example in both databases, the difference becomes pretty obvious: PostgreSQL makes the relationships visible, while MongoDB makes the full visit easier to read in one place.

If you want to read more practical MongoDB guides, you can find them here: MongoDB Articles.

Top comments (0)