Back to Study Material Python

MongoDB Introduction

Before working with MongoDB in Python, it helps to understand its core concepts and how they differ from relational databases. MongoDB uses its own vocabul...

MongoDB Introduction

Introduction to MongoDB: Concepts and Core Terminology

Before working with MongoDB in Python, it helps to understand its core concepts and how they differ from relational databases. MongoDB uses its own vocabulary, and mapping these terms to familiar SQL concepts makes learning it much faster.

In MongoDB, a database is the top-level container, equivalent to a database in SQL. Inside a database, data is organized into collections, which correspond roughly to SQL tables. A collection holds documents, which are the individual data records. Each document is similar to a row in a SQL table but stored as a flexible BSON object (Binary JSON) that can have nested objects and arrays.

The mapping looks like this: SQL: Database -> Table -> Row -> Column MongoDB: Database -> Collection -> Document -> Field

Every document in MongoDB automatically receives a unique identifier stored in the _id field. By default this is an ObjectId, a 12-byte BSON type that encodes the creation timestamp, machine identifier, and a random counter. You can also provide your own _id value.

MongoDB does not require all documents in a collection to have the same fields. This is the key difference from SQL tables where every row must match the table's column definitions. This schema flexibility allows iterative development where the data model evolves without costly ALTER TABLE migrations.

MongoDB's query system is expressive. You query by constructing a filter dictionary where each key-value pair specifies a field and what it should match. Simple equality checks are straightforward, and range queries, pattern matching, and logical operators are all expressed as nested dictionaries:

# Find students in grade range 80-95 filter_query = {"grade": {"$gte": 80, "$lte": 95}}

MongoDB also supports indexes, which speed up queries on specific fields just as in SQL. Creating an index on the name field makes find({"name": "Alice"}) much faster on large collections. Without indexes, MongoDB performs a full collection scan.

The aggregation pipeline is MongoDB's equivalent to SQL GROUP BY and complex SELECT statements. You chain stages like $match (filter), $group (aggregate), $sort, and $project (select fields) to build complex data transformations.

Exam tip: Know the four main CRUD operations in PyMongo: insert_one, find, update_one, and delete_one. Also know their plural counterparts: insert_many, find (returns all matching), update_many, and delete_many. Understand that find() returns a cursor, not a list, and that you need to iterate over it or call list() to get all results.