MongoDB
MongoDB is a document-oriented NoSQL database that stores data as JSON-like documents called BSON (Binary JSON). Unlike relational databases, MongoDB does ...
Using MongoDB with Python via PyMongo
MongoDB is a document-oriented NoSQL database that stores data as JSON-like documents called BSON (Binary JSON). Unlike relational databases, MongoDB does not require a fixed schema. Each document in a collection can have different fields. This flexibility makes MongoDB well-suited for rapidly changing data models, content management, real-time analytics, and applications where the data structure varies per record.
To connect Python to MongoDB, you use the PyMongo library:
pip install pymongo
Connecting and performing basic operations is straightforward:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/") db = client["school"] students = db["students"]
# Insert a document students.insert_one({"name": "Eve", "grade": 91, "subjects": ["Math", "Physics"]})
# Insert multiple documents students.insert_many([ {"name": "Frank", "grade": 78}, {"name": "Grace", "grade": 95, "graduated": True} ])
# Query documents for student in students.find({"grade": {"$gt": 80}}): print(student)
# Update a document students.update_one({"name": "Frank"}, {"$set": {"grade": 82}})
# Delete a document students.delete_one({"name": "Eve"})
client.close()
MongoDB's query language uses operators like $gt (greater than), $lt (less than), $in (matches any value in a list), and $regex (matches a regular expression pattern). These operators appear as keys in query dictionaries.
MongoDB is particularly powerful for embedded documents and arrays. Instead of joining tables like in SQL, you can store all related data inside a single document. A student document could contain an array of course objects, each with name, grade, and instructor, all in one record.
The flexibility comes with trade-offs. Without schema enforcement, invalid data can slip in. MongoDB 3.6 and later supports JSON Schema validation to address this. Transactions across multiple documents were also added in later versions, reducing one of MongoDB's traditional weaknesses.
Interview tip: The main comparison interviewers expect is between relational (SQL) and document (NoSQL) models. SQL enforces a rigid schema and uses JOINs for related data. MongoDB allows flexible schemas and embeds related data. Choose MongoDB when your schema changes frequently or when the data is naturally hierarchical and document-like.