Code Dogs Technical Documentation
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Pymongo Cheat Sheet

Install

pip install pymongo==3.5.1

Imports

import os
from typing import List
import pymongo
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.database import Database

Connection

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)

Collections

# 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()