Databases 14 min read

Master MongoDB with Python: Complete Guide to CRUD Operations

This tutorial walks through installing MongoDB and PyMongo, establishing a connection, selecting databases and collections, and demonstrates how to insert, query, count, sort, skip, limit, update, and delete documents using both legacy and modern PyMongo methods, complete with code examples and operator references.

Data STUDIO
Data STUDIO
Data STUDIO
Master MongoDB with Python: Complete Guide to CRUD Operations

1. Preparation

Ensure MongoDB is installed and running, and install the PyMongo library for Python 3.

2. Connect to MongoDB

Use MongoClient from PyMongo, passing the host and port (default 27017) or a full connection string.

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# or
client = MongoClient('mongodb://localhost:27017/')

3. Select a Database

Access a database (e.g., test) via attribute or dictionary syntax.

db = client.test
# or
db = client['test']

4. Select a Collection

Choose a collection (e.g., students) similarly.

collection = db.students
# or
collection = db['students']

5. Insert Data

Insert a single document using insert (deprecated) or the recommended insert_one and insert_many.

student = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
result = collection.insert(student)
print(result)  # returns the generated _id

# Insert multiple documents
students = [student1, student2]
result = collection.insert(students)
print(result)  # list of _id values

Modern API:

result = collection.insert_one(student)
print(result.inserted_id)

result = collection.insert_many([student1, student2])
print(result.inserted_ids)

6. Query

Retrieve documents with find_one (single result) or find (cursor). Example:

result = collection.find_one({'name': 'Mike'})
print(result)

Query by ObjectId requires importing from bson.objectid:

from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
print(result)

Use comparison operators in queries:

results = collection.find({'age': {'$gt': 20}})
for r in results:
    print(r)
$lt

– less than –

{'age': {'$lt': 20}}
$gt

– greater than –

{'age': {'$gt': 20}}
$lte

– less than or equal –

{'age': {'$lte': 20}}
$gte

– greater than or equal –

{'age': {'$gte': 20}}
$ne

– not equal –

{'age': {'$ne': 20}}
$in

– in list –

{'age': {'$in': [20, 23]}}
$nin

– not in list – {'age': {'$nin': [20, 23]}} Regular‑expression query example:

results = collection.find({'name': {'$regex': '^M.*'}})
$regex

– matches a regular expression (e.g., ^M.* matches names starting with M) $exists – checks field existence $type – checks field type $mod – modulus operation $text – text search $where – JavaScript expression

7. Count

Use count() on a cursor to get the number of matching documents.

count = collection.find().count()
print(count)

8. Sort

Sort results with sort(), specifying the field and direction ( pymongo.ASCENDING or pymongo.DESCENDING).

results = collection.find().sort('name', pymongo.ASCENDING)
print([r['name'] for r in results])

9. Skip and Limit

Use skip() to offset results and limit() to restrict the number returned.

results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([r['name'] for r in results])

For very large collections, avoid large skips; instead query by a greater _id value.

10. Update

Legacy update is deprecated. Use update_one, update_many, or replace_one with update operators such as $set or $inc.

# Update a single document
condition = {'name': 'Kevin'}
result = collection.update_one(condition, {'$set': {'age': 25}})
print(result.matched_count, result.modified_count)

# Increment age for all documents where age > 20
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result.matched_count, result.modified_count)

11. Delete

Use delete_one or delete_many (preferred) to remove documents.

result = collection.delete_one({'name': 'Kevin'})
print(result.deleted_count)

result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)

12. Other Operations

PyMongo also provides combined methods such as find_one_and_delete, find_one_and_replace, and find_one_and_update, as well as index management methods ( create_index, drop_index, etc.). Refer to the official PyMongo documentation for full details.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databasecrudtutorialMongoDBquerypymongo
Data STUDIO
Written by

Data STUDIO

Click to receive the "Python Study Handbook"; reply "benefit" in the chat to get it. Data STUDIO focuses on original data science articles, centered on Python, covering machine learning, data analysis, visualization, MySQL and other practical knowledge and project case studies.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.