Pymongo Cheat Sheet
pip install pymongo==3.5.1
import os
from typing import List
import pymongo
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.database import Database
export MONGO_URI="mongodb://username:password@localhost:27017"
export MONGO_NAME="some-db"
try:
mongo_client = MongoClient(os.environ.get('MONGO_URI', ''))
db = mongo_client[os.environ.get('MONGO_NAME', '')]
except Exception as err:
print(f'! error connecting to mongodb: {err}')
exit(1)
# List existing
collections: List[str] = db.list_collection_names()
print(collections)
# Create new
my_collection: Collection = db["my-collection"]
my_collection.create_index('timestamp', name='unq-ts', unique=True)
# Drop existing and it's index
my_collection.drop_index('unq-ts')
my_collection.drop()