← Back to Python Course | Chapter 13: Data Science & Web | Lesson 14 of 14

Python MongoDB

MongoDB is a database that stores information as flexible labeled documents, like index cards with different notes on them. Python can add, find, change, and delete those cards.
Syntax
python
from pymongo import MongoClient

client = MongoClient("connection_string")
collection = client["database"]["collection"]
collection.insert_one({"key": value})

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

python
# 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

python
from unittest.mock import MagicMock

collection = MagicMock()  # stands in for a real MongoDB collection
collection.insert_one({"name": "Alex"})  # adds a single document
collection.insert_many([{"name": "Sam"}, {"name": "Jo"}])  # adds several documents at once
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

python
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"}))  # returns the first match, or None
print(list(collection.find({})))  # empty filter matches every document

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

python
from unittest.mock import MagicMock

collection = MagicMock()
collection.update_one({"name": "Alex"}, {"$set": {"age": 31}})  # $set changes only this field
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

python
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)  # how many documents were actually removed
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to start the MongoDB server or check the connection string, so operations fail with a connection timeout.
  2. Calling insert_one() twice with the same _id, which raises DuplicateKeyError.
  3. Updating with a plain dictionary such as update_one(f, {"age": 5}), which raises an error; use an operator like {"$set": {"age": 5}}.
Chapter Summary
  • NumPy, Pandas, and Matplotlib work with numerical data, tables, and charts.
  • Statistics, CSV analysis, and data visualization support data tasks.
  • requests, JSON, web scraping, Flask, Django, and MongoDB connect Python to the web and databases.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.