reference

MongoDB with PyMongo Guide

Quick guide to connecting and working with MongoDB using Python's PyMongo library.

Published: November 8, 2024

MongoDB with PyMongo

Installation

pip install pymongo

Connection

Basic Connection

from pymongo import MongoClient

# Connection string format
client = MongoClient('mongodb://<username>:<password>@<ip>:<port>/<database>?authSource=<database>')

# Get database
db = client['db_name']

# List collections
db.collection_names()

Connection String Components

ComponentDescription
usernameMongoDB username
passwordUser password
ipServer IP or hostname
portMongoDB port (default: 27017)
databaseTarget database name
authSourceAuthentication database

Basic Operations

Insert

# Insert one
db.collection.insert_one({"name": "John", "age": 30})

# Insert many
db.collection.insert_many([
    {"name": "Jane", "age": 25},
    {"name": "Bob", "age": 35}
])

Find

# Find one
doc = db.collection.find_one({"name": "John"})

# Find all
for doc in db.collection.find():
    print(doc)

# Find with filter
docs = db.collection.find({"age": {"$gt": 25}})

Update

# Update one
db.collection.update_one(
    {"name": "John"},
    {"$set": {"age": 31}}
)

# Update many
db.collection.update_many(
    {"age": {"$lt": 30}},
    {"$set": {"status": "young"}}
)

Delete

# Delete one
db.collection.delete_one({"name": "John"})

# Delete many
db.collection.delete_many({"age": {"$lt": 25}})

Quick Reference

OperationMethod
Insert oneinsert_one(doc)
Insert manyinsert_many([docs])
Find onefind_one(filter)
Find allfind(filter)
Update oneupdate_one(filter, update)
Update manyupdate_many(filter, update)
Delete onedelete_one(filter)
Delete manydelete_many(filter)
Countcount_documents(filter)

Tags

mongodbpythonpymongodatabasenosql

Found this useful?

Subscribe to get more cheatsheets and resources.