Sobes.tech
Middle

MongoDB vs PostgreSQL — what is the difference?

sobes.tech AI

Answer from AI

MongoDB and PostgreSQL are two different database management systems, each suitable for different tasks.

MongoDB is a document-oriented NoSQL database. It stores data in BSON format (extended JSON), allowing flexible handling of unstructured or semi-structured data. MongoDB is well-suited for projects where the data schema may frequently change, such as startups, prototypes, and applications with dynamic data.

PostgreSQL is a relational DBMS supporting ACID, complex queries, and transactions. It uses a strict schema with tables and relations, ensuring data integrity and powerful capabilities for analytics and complex business logic. PostgreSQL is suitable for systems where reliability, consistency, and complex queries are important, such as banking systems and ERP.

Key differences:

  • Data model: MongoDB — document-oriented, PostgreSQL — relational.
  • Schema: MongoDB — flexible, PostgreSQL — strict.
  • Transactions: PostgreSQL supports full transactions, MongoDB — with limitations (improved in recent versions).
  • Scalability: MongoDB is easier to scale horizontally.

Example of using MongoDB in Python with pymongo library:

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['users']
collection.insert_one({'name': 'Ivan', 'age': 30})
user = collection.find_one({'name': 'Ivan'})
print(user)

Example of connecting to PostgreSQL with psycopg2:

import psycopg2
conn = psycopg2.connect(dbname='mydb', user='user', password='pass', host='localhost')
cursor = conn.cursor()
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ('Ivan', 30))
conn.commit()
cursor.execute("SELECT * FROM users WHERE name = %s", ('Ivan',))
print(cursor.fetchone())
cursor.close()
conn.close()