Databases 7 min read

MongoDB CRUD Operations with PyMongo in Python

This tutorial demonstrates how to install PyMongo, connect to a MongoDB server, and perform comprehensive CRUD operations, query filters, array manipulations, and nested field updates using Python code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
MongoDB CRUD Operations with PyMongo in Python

The article provides a step‑by‑step guide for using the PyMongo driver to interact with MongoDB from Python, covering installation, connection, and a wide range of CRUD operations.

Dependencies: Install the driver with pip install pymongo and ensure a running MongoDB instance.

Connection example:

from pymongo import MongoClient
client = MongoClient('mongodb://127.0.0.1:27017')
db = client.express
print(db.collection_names())
collection = db.delivery

Basic queries such as listing collections, finding documents, and printing results are shown, e.g.,

for row in collection.find({}):
    print(row.values())

Update operations: The guide illustrates field updates with $set , conditional updates, and options like upsert and multi . Example to change age to 50:

my_set.update({"name":"zhangsan"},{"$set":{"age":50}})

Delete operations: Documents can be removed using remove with optional query criteria, e.g.,

my_set.remove({'name': 'zhangsan'})
my_set.remove(id)
db.users.remove()

Query operators: The article lists common MongoDB operators and shows Python usage, including $gt , $lt , $gte , $lte , $in , $or , $all , and array modifiers like $push , $pushAll , $pop , $pull , $pullAll . Sample snippets:

# age > 25
for i in my_set.find({"age": {"$gt": 25}}):
    print(i)

# $or example
for i in my_set.find({"$or": [{"age": 20}, {"age": 35}]}):
    print(i)

Nested field operations: Using dot notation to query and update embedded documents, for example:

# query nested field
for i in my_set.find({"contact.iphone": "11223344"}):
    print(i)

# update nested field
my_set.update({"contact.iphone": "11223344"}, {"$set": {"contact.email": "[email protected]"}})

A complete class MyMongoDB is provided, encapsulating insert , update , delete , and find methods, and demonstrating usage in a main function.

The article ends with a call to follow the author for more automation learning resources.

PythonDatabaseCRUDMongoDBQueryPyMongo
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login 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.