Databases 13 min read

Master MongoDB with PyMongo: Essential CRUD Operations in Python

Learn how to connect to MongoDB using PyMongo, create databases and collections, and perform essential CRUD operations—including inserting single or multiple documents, querying with filters and regex, updating records with update_one and update_many, counting, sorting, pagination, and deleting—complete with Python code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master MongoDB with PyMongo: Essential CRUD Operations in Python

MongoDB is a C++-written NoSQL database that stores JSON-like documents; this guide shows how to use MongoDB with Python3 via PyMongo.

1. Preparation

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

2. Connect to MongoDB

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

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)

Or using a connection string:

client = MongoClient('mongodb://localhost:27017/')

3. Select Database

Specify the database, e.g., test:

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

4. Select Collection

Declare a collection, e.g., students:

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

5. Insert Data

Insert a single document:

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

Insert multiple documents with insert_many (or insert_one for a single record):

student1 = {'id':'20170101','name':'Jordan','age':20,'gender':'male'}
student2 = {'id':'20170202','name':'Mike','age':21,'gender':'male'}
result = collection.insert_many([student1, student2])
print(result.inserted_ids)

6. Query

Use find_one for a single result or find for a cursor of multiple results.

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

Query by ObjectId:

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

Range and regex queries use operators such as $gt, $lt, $regex, etc.

7. Count

Count documents with count() on a cursor.

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

8. Sort

Sort results with sort() and specify ascending or descending.

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

9. Skip & Limit

Use skip() and limit() for pagination.

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

10. Update

Update a document with update_one or update_many, typically using $set or other operators.

condition = {'name':'Kevin'}
result = collection.update_one(condition, {'$set': {'age':25}})
print(result.modified_count)

11. Delete

Delete documents with delete_one or delete_many (or the older remove).

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

12. Additional Operations

PyMongo also provides methods such as find_one_and_update, create_index, and others for advanced use.

PythondatabaseCRUDMongoDBPyMongo
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

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.