Databases 9 min read

Master MongoDB with Python: Complete Pymongo CRUD Guide

This tutorial walks you through installing pymongo, connecting to MongoDB with and without authentication, performing insert, update, delete, query, and index operations, and demonstrates each step with clear Python code snippets and illustrative screenshots.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master MongoDB with Python: Complete Pymongo CRUD Guide

Introduction

MongoDB is a widely used NoSQL database; this article demonstrates how to use it from Python via the pymongo driver.

1. Install pymongo

pip install pymongo
from pymongo import MongoClient

2. Connect to MongoDB

2.1 Simple (guest) connection

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

2.2 Authenticated connection

MongoClient('mongodb://hwzjj:123456@localhost:27017/hw')

This connects with username hwzjj and password 123456.

3. Insert operations

Create two collections, student and teacher, then insert documents.

db.createCollection(name='student', option={capped:true, autoIndexId:true, size:100, max:1000})
db.createCollection(name='teacher', option={capped:true, autoIndexId:true, size:200, max:2000})
show collections;

Insert a single document into the student collection:

from pymongo import MongoClient
client = MongoClient('mongodb://hwzjj:123456@localhost:27017/hw')
db = client['hw']
coll = db['student']
res = {'id':'0003','name':'任性','age':43}
first = coll.insert_one(res)
print(first.inserted_id)

Insert a document into a newly created teacher collection:

from pymongo import MongoClient
client = MongoClient('mongodb://hwzjj:123456@localhost:27017/hw')
db = client['hw']
db.create_collection('teacher')
res = {'id':'0001','name':'boy','age':36}
last = db.student.insert_one(res)
print(last.inserted_id)

Bulk insert 100,000 documents:

import random
from pymongo import MongoClient
client = MongoClient('mongodb://hwzjj:123456@localhost:27017/hw')
db = client['hw']
coll = db['student']

def get():
    for y in range(100000):
        data = {'id':y,'name':'user--'+str(y),'age':random.choice(range(100))}
        yield data

for y in get():
    coll.insert(y)

Note: inserting 100,000 records is slightly slower than MySQL; insert can insert up to four identical records at once.

4. Update operations

Update the first matching document:

from pymongo import MongoClient
client = MongoClient('mongodb://hwzjj:123456@localhost:27017/hw')
db = client['hw']
coll = db['student']
coll.update_one({'name':'user--10'},{'$set':{'name':'用户已注销'}})

Update all matching documents (after inserting four identical records):

coll.update({'name':'hw'},{'$set':{'name':'用户已注册'}})

5. Delete operations

Delete all documents matching a condition:

from pymongo import MongoClient
client = MongoClient('mongodb://hwzjj:123456@localhost:27017/hw')
db = client['hw']
coll = db['student']
coll.remove({'name':'hw'})  # or coll.delete_many({'name':'hw'})

Delete the first document matching a condition:

coll.delete_one({'name':'hw'})

6. Query operations

Find the first matching document, all matching documents, find‑and‑remove, find‑and‑replace, find‑and‑update, count, sort, skip, limit, and lookup by _id are demonstrated with screenshots (images omitted for brevity).

7. Index operations

Create an index on the name field:

coll.create_index('name')

List all indexes:

for y in coll.list_indexes():
    print(y)

Drop the name index (the default _id index cannot be removed):

coll.drop_index('name_1')

Conclusion

After completing this guide you should be comfortable performing common development tasks with pymongo, and you can explore more advanced features as needed.

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.

MongoDBNoSQLpymongo
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.