Databases 14 min read

Master MongoDB with Python: Complete Guide to CRUD Operations

This tutorial explains how to install PyMongo, connect to local or remote MongoDB instances, choose databases and collections, and perform all common CRUD operations—including inserts, queries, updates, deletions, and special cases—using Python code examples and practical tips.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Master MongoDB with Python: Complete Guide to CRUD Operations

1 Connect to Database

1.1 Install PyMongo

Use pip to install the PyMongo library, which enables Python to communicate with MongoDB.

<code>python3 -m pip install pymongo</code>

You can also install a specific version or upgrade the package:

<code>python3 -m pip install pymongo==3.5.1</code>
<code>python3 -m pip install --upgrade pymongo</code>

1.2 Create a MongoClient

Initialize a connection to MongoDB. For a local instance without authentication:

<code>import pymongo
conn = pymongo.MongoClient()</code>

For a remote server, provide a URI that includes username, password, host and port:

<code>import pymongo
conn = pymongo.MongoClient('mongodb://test:[email protected]:27019')</code>

If the server does not require authentication, omit the credentials:

<code>import pymongo
conn = pymongo.MongoClient('mongodb://45.10.110.77:27019')</code>

1.3 Select Database and Collection

Two common ways exist to obtain a database and a collection.

Method 1 – attribute style:

<code>from pymongo import MongoClient
conn = MongoClient()
database = conn.chapter_1
collection = database.example_data_1</code>

Method 2 – dictionary‑style indexing (useful for variable names):

<code>from pymongo import MongoClient
db_name = 'chapter_1'
collection_name = 'example_data_1'
conn = MongoClient()
 database = conn[db_name]
 collection = database[collection_name]
</code>

Both methods are equivalent; the second is handy when iterating over multiple databases or collections.

Note: A collection is created only after the first document is inserted.

2 MongoDB Commands Mapped to PyMongo Methods

Most MongoDB shell commands correspond directly to PyMongo methods, with naming converted from camelCase to snake_case.

insertOne → insert_one

insertMany → insert_many

find → find

updateOne → update_one

updateMany → update_many

deleteOne → delete_one

deleteMany → delete_many

3 Inserting Data

Basic Syntax

<code>collection.insert_one(document)      # single document
collection.insert_many([doc1, doc2]) # multiple documents
</code>

Example

<code>collection.insert_many([
    {'name': '王小二','age':21,'student':True,'address':'广州'},
    {'name': '赵小三','age':20,'student':True,'address':'北京'},
    {'name': '钱小四','age':21,'student':True,'address':'上海'},
    {'name': '孙小五','age':20,'student':True,'address':'山东'},
    {'name': '李小六','age':None,'student':True,'address':'河北'},
    {'name': '欧阳小七','age':24,'student':False,'address':'杭州'},
    {'name': '公孙小八','age':25,'student':False,'address':'广州'}
])
</code>
PyMongo automatically creates the database and collection if they do not already exist.

4 Querying Data

Find One Document

<code>from pymongo import MongoClient
conn = MongoClient()
collection = conn.chapter_1.example_data_1
print(collection.find_one({}))
</code>

Find All Documents

<code>for doc in collection.find():
    print(doc)
</code>

Conditional Queries

<code>rows = collection.find({
    'age': {'$gt': 21, '$lt': 25},
    'name': {'$ne': '公孙小八'}
})
for r in rows:
    print(r)
</code>

Sorting and Distinct

<code># Sort by age descending
rows = collection.find().sort('age', -1)
# Distinct values of a field
unique_ages = collection.distinct('age')
</code>
When sorting large result sets, avoid executing the operation directly in GUI tools to prevent freezing.

5 Updating and Deleting Documents

Update Syntax

<code># Update a single document
collection.update_one({'name': '公孙小八'}, {'$set': {'age': 80, 'address': '美国'}})
# Update many documents
collection.update_many({'student': False}, {'$set': {'status': 'inactive'}})
# Upsert (insert if not found)
collection.update_one({'name': '隐身人'}, {'$set': {'age': 0, 'address': '里世界'}}, upsert=True)
</code>

Delete Syntax

<code># Delete one matching document
collection.delete_one({'age': 0})
# Delete all matching documents
collection.delete_many({'age': 0})
</code>
Always preview the documents with a find query before performing delete operations.

6 Special Cases When Translating MongoDB Commands to PyMongo

Null Values

MongoDB uses

null

; Python uses

None

. Replace

null

with

None

in queries.

Boolean Values

MongoDB uses

true

/

false

; Python uses

True

/

False

. Adjust the case accordingly.

Sorting Parameters

In the shell,

sort({field: 1})

is used. In PyMongo, call

sort('field', 1)

or

sort('field', -1)

.

Querying by _id

Import

ObjectId

from the

bson

package and use it in the query:

<code>from bson import ObjectId
collection.find({'_id': ObjectId('5e8ac5dfdd9cf99b7a446e99')})
</code>

Conclusion

The article introduced MongoDB installation, demonstrated how to use the graphical tool Robo 3T, and showed that most MongoDB operations can be directly ported to Python with PyMongo. Only a few edge cases—null handling, boolean literals, sorting syntax, and _id queries—require minor adjustments.

PythonDatabaseCRUDMongoDBNoSQLPyMongo
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

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.