5.5. Database MongoDB

5.5.1. Install

$ pip install pymongo

5.5.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('...')

5.5.3. Select all records

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

5.5.4. Filter records

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