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

Python MongoDB

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()
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

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"}))
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

python
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

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)

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.