4.4. Database MongoDB

4.4.1. Install

$ pip install pymongo

4.4.2. Insert data

from datetime import datetime, timezone
from pymongo import MongoClient

DATA = {
    'name': 'José Jiménez',
    'catchphrase': 'My name... José Jiménez',
    'tags': ['astronaut', 'nasa', 'space'],
    'date': datetime.now(tz=timezone.utc)
}


client = MongoClient('mongodb://example.com:27017/')
db = client.test_database
astronauts = db.astronauts

obj = astronauts.insert_one(DATA)
obj.inserted_id
# ObjectId('...')

4.4.3. Select all records

for astro in astronauts.find():
    print(astro)

4.4.4. Filter records

for astro in astronauts.find({'name': 'José Jiménez'}):
    print(astro)