Python MongoDB
In this page:
Connecting to MongoDB
The pymongo library is the standard driver for talking to MongoDB from Python — you create a MongoClient pointed at your connection string, then select a database and collection off of it, similar in spirit to how mysql.connector opens a connection in the relational world covered elsewhere on this site.
Example: Connecting to MongoDB
# pip install pymongo
from unittest.mock import MagicMock
client = MagicMock()
db = client["mydb"]
collection = db["users"]
print(type(collection))
Inserting Documents
insert_one() adds a single document (a Python dict) to a collection, and insert_many() takes a list of dicts to add several at once — unlike a SQL table, MongoDB documents in the same collection don't need identical fields, since it's a schemaless document store.
Example: Inserting Documents
from unittest.mock import MagicMock
collection = MagicMock()
collection.insert_one({"name": "Alex"})
collection.insert_many([{"name": "Sam"}, {"name": "Jo"}])
print("Documents inserted")
Querying Documents
find_one() returns the first matching document or None, while find() returns a cursor you iterate over to get every match — passing an empty dict {} as the filter to find() matches every document in the collection, similar to a SQL query with no WHERE clause.
Example: Querying Documents
from unittest.mock import MagicMock
collection = MagicMock()
collection.find_one.return_value = {"name": "Alex"}
collection.find.return_value = [{"name": "Alex"}, {"name": "Sam"}]
print(collection.find_one({"name": "Alex"}))
print(list(collection.find({})))
Updating Documents
update_one() modifies the first matching document, and it requires an update operator like $set to specify which fields change — forgetting $set and passing the replacement fields directly would instead replace the entire document, wiping out any fields you didn't include.
Example: Updating Documents
from unittest.mock import MagicMock
collection = MagicMock()
collection.update_one({"name": "Alex"}, {"$set": {"age": 31}})
print("Document updated with $set")
Deleting Documents
delete_one() removes the first matching document and delete_many() removes every match — both return a result object whose deleted_count tells you how many documents were actually removed, which is worth checking since a filter that matches nothing silently deletes zero documents rather than raising an error.
Example: Deleting Documents
from unittest.mock import MagicMock
collection = MagicMock()
collection.delete_one.return_value.deleted_count = 1
result = collection.delete_one({"name": "Alex"})
print(result.deleted_count)
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB