iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python MongoDB

Talk to MongoDB from Python with PyMongo, the official driver. Documents look just like Python dicts.

Install

SHELL
pip install pymongo

Connect

PYTHON
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db    = client['shop']
users = db['users']

Insert

PYTHON
users.insert_one({'name': 'Ada', 'age': 36, 'roles': ['admin']})
users.insert_many([
    {'name': 'Grace', 'age': 56},
    {'name': 'Linus', 'age': 42},
])

Find

PYTHON
print(users.find_one({'name': 'Ada'}))

# All adults sorted by name
for u in users.find({'age': {'$gte': 18}}).sort('name'):
    print(u['name'])

Update & delete

PYTHON
users.update_one({'name': 'Ada'},
                 {'$set': {'email': 'ada@example.com'}})

users.update_many({}, {'$inc': {'visits': 1}})

users.delete_one({'name': 'Linus'})
users.delete_many({'age': {'$lt': 18}})

Aggregations

PYTHON
pipeline = [
    {'$match': {'age': {'$gte': 18}}},
    {'$group': {'_id': '$country', 'count': {'$sum': 1}}},
    {'$sort':  {'count': -1}},
]
for doc in users.aggregate(pipeline):
    print(doc)

Indexes

PYTHON
users.create_index('email', unique=True)
users.create_index([('country', 1), ('created_at', -1)])
Tip: For async use motor (Mongo's async driver) or beanie (a Pydantic-based ODM on top of motor).

Example

Example
# from pymongo import MongoClient
# c = MongoClient('mongodb://localhost:27017/')
# users = c['shop']['users']
# users.insert_one({'name': 'Ada', 'age': 36})
# for u in users.find(): print(u)
print('Use PyMongo for MongoDB.')
Try it Yourself »

Exercise

Official synchronous Mongo driver.

import

Test yourself

Q1. The official sync driver is…
Q2. Insert one doc with…
Q3. Async Mongo driver is…

Discussion

Loading…