├── .gitignore ├── LICENSE ├── README.md ├── docker-compose.yaml ├── src ├── chart.py ├── collection_create.py ├── db_client.py ├── example.env ├── generate_data.py └── requirements.txt └── ts-pymongo.code-workspace /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Coding For Entrepreneurs 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Time Series with Python & MongoDB 2 | 3 | Learn the fundamental techniques for analyzing time-series data with Python, MongoDB, PyMongo, Pandas, & Matplotlib 4 | 5 | *References* 6 | - Blog post *(coming soon)* 7 | - Video *(coming soon)* 8 | 9 | *Prerequisites* 10 | - Python 3.8+ Installed 11 | - [Docker Desktop](https://www.docker.com/products/docker-desktop/) Installed (for local MongoDB instance) 12 | - Terminal or PowerShell experience 13 | 14 | 15 | ## Getting Started 16 | 17 | 1. Make a project directory 18 | ``` 19 | mkdir -p ~/dev/ts-pymongo 20 | cd ~/dev/ts-pymongo 21 | ``` 22 | 2. Clone this repo: 23 | 24 | ``` 25 | git clone https://github.com/codingforentrepreneurs/time-series-mongodb-pymongo . 26 | ``` 27 | 28 | 3. Make and activate a virtual environment: 29 | 30 | ``` 31 | python3.10 -m venv venv 32 | ``` 33 | 34 | 35 | *macOS/Linux activation* 36 | ``` 37 | source venv/bin/activate 38 | ``` 39 | 40 | *Windows activation* 41 | ``` 42 | ./venv/Scripts/activate 43 | ``` 44 | 45 | 4. Upgrade Virtual Environment Pip 46 | ``` 47 | (venv) python -m pip install pip --upgrade 48 | ``` 49 | 50 | 5. Move `src/example.env` to `src/.env` 51 | ``` 52 | mv src/example.env src/.env 53 | ``` 54 | 55 | 6. Change `MONGO_INITDB_ROOT_PASSWORD` in `.env` 56 | Create a new password with: 57 | 58 | ``` 59 | (venv) python -c "import secrets;print(secrets.token_urlsafe(32))" 60 | ``` 61 | 62 | So `.env` looks like: 63 | 64 | ``` 65 | MONGO_INITDB_ROOT_USERNAME="root" 66 | MONGO_INITDB_ROOT_PASSWORD="wlke0lL-v7FkGFn5Cl0brfxHJqhDPImBmg-MRfCIXx4" 67 | ``` 68 | 69 | 7. Install requirements 70 | 71 | ``` 72 | (venv) python -m pip install -r src/requirements.txt 73 | ``` 74 | 75 | 8. Run Docker Compose 76 | Don't have docker? Install [Docker Desktop](https://www.docker.com/products/docker-desktop/) 77 | 78 | ``` 79 | cd ~/dev/ts-pymongo 80 | docker compose up 81 | ``` 82 | 83 | 84 | 9. Checkout the Final Results 85 | If you want to see the final code changes, checkout the `final` branch. 86 | ``` 87 | git checkout final 88 | ``` 89 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.9' 2 | 3 | services: 4 | mongo: 5 | image: mongo 6 | restart: always 7 | ports: 8 | - 27017:27017 9 | env_file: ./src/.env -------------------------------------------------------------------------------- /src/chart.py: -------------------------------------------------------------------------------- 1 | # blank on purpose - check `final` branch -------------------------------------------------------------------------------- /src/collection_create.py: -------------------------------------------------------------------------------- 1 | # incomplete on purpose - check `final` branch 2 | 3 | from pymongo import errors 4 | 5 | 6 | # fix local imports 7 | # import db_client 8 | 9 | def create_ts(name='rating_over_time'): 10 | """ 11 | Create a new time series collection 12 | """ 13 | # 1. get a mongodb client 14 | # 2. get a mongodb database 15 | try: 16 | # 3. create a collection 17 | pass 18 | except errors.CollectionInvalid as e: 19 | print(f"{e}. Continuing") 20 | 21 | def drop(name='rating_over_time'): 22 | """ 23 | Drop any given collection by name 24 | """ 25 | # 1. get a mongodb client 26 | # 2. get a mongodb database 27 | try: 28 | # 3. Drop a collection 29 | pass 30 | except errors.CollectionInvalid as e: 31 | print(f"Collection error:\n {e}") 32 | raise Exception("Cannot continue") -------------------------------------------------------------------------------- /src/db_client.py: -------------------------------------------------------------------------------- 1 | # blank on purpose - check `final` branch -------------------------------------------------------------------------------- /src/example.env: -------------------------------------------------------------------------------- 1 | MONGO_INITDB_ROOT_USERNAME="root" 2 | MONGO_INITDB_ROOT_PASSWORD="make-a-better-one" -------------------------------------------------------------------------------- /src/generate_data.py: -------------------------------------------------------------------------------- 1 | # incomplete on purpose - check `final` branch 2 | import datetime 3 | import random 4 | import sys 5 | 6 | # fix local imports 7 | # import collection_create 8 | # import db_client 9 | 10 | 11 | 12 | name_choices = ["Big", "Goat", "Chicken", "Tasty", "Salty", "Fire", "Forest", "Moon", "State", "Texas", "Bear", "California"] 13 | cuisine_choices = ["Pizza", "Bar Food", "Fast Food", "Pasta","Tacos", "Sushi", "Vegetarian", "Steak", "Burgers"] 14 | 15 | 16 | def get_random_name(): 17 | _name_start = random.choice(name_choices) 18 | _name_end = random.choice(name_choices) 19 | return f"{_name_start} {_name_end}" 20 | 21 | def get_random_cuisine(): 22 | selected_cuisine = random.choice(cuisine_choices) 23 | return selected_cuisine 24 | 25 | def get_random_rating(skew_low=True): 26 | part_a = list([random.randint(1, 3) for i in range(10)]) 27 | part_b = list([random.randint(3, 4) for i in range(10)]) 28 | if not skew_low: 29 | part_c = list([random.randint(4, 5) for i in range(25)]) 30 | else: 31 | part_c = list([random.randint(4, 5) for i in range(5)]) 32 | _ratings = part_a + part_b + part_c 33 | return random.choice(_ratings) 34 | 35 | def get_random_timestamp(): 36 | now = datetime.datetime.now() 37 | delta = now - datetime.timedelta(days=random.randint(0, 5_000), minutes=random.randint(0, 60), seconds=random.randint(0, 60)) 38 | return delta 39 | 40 | # create get_or_generate_collection function 41 | 42 | def run(collection, iterations=50, skew_results=True): 43 | completed = 0 44 | for n in range(0, iterations): 45 | timestamp = get_random_timestamp() 46 | name = get_random_name() 47 | cuisine = get_random_cuisine() 48 | rating = get_random_rating(skew_low=True) 49 | if skew_results: 50 | if cuisine.lower() == "mexican": 51 | rating = random.choice([4, 5]) 52 | elif cuisine.lower() == "bar food": 53 | rating = random.choice([1, 2]) 54 | elif cuisine.lower() == "sushi": 55 | rating = get_random_rating(skew_low=False) 56 | data = { 57 | "metadata": { 58 | "name": name, 59 | "cuisine": cuisine 60 | }, 61 | "rating": rating, 62 | "timestamp": timestamp 63 | } 64 | # send to database 65 | print(data) 66 | if n > 0 and n % 1000 == 0: 67 | print(f"Finished {n} of {iterations} items.") 68 | print(f"Added {completed} items.") 69 | 70 | 71 | if __name__ == "__main__": 72 | iterations = 50 73 | name="rating_over_time" 74 | try: 75 | iterations = int(sys.argv[1]) 76 | except: 77 | pass 78 | try: 79 | name= sys.argv[2] 80 | except: 81 | pass 82 | collection = None 83 | run(collection, iterations=iterations) -------------------------------------------------------------------------------- /src/requirements.txt: -------------------------------------------------------------------------------- 1 | pymongo 2 | python-decouple 3 | pandas 4 | matplotlib -------------------------------------------------------------------------------- /ts-pymongo.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ], 7 | "settings": {} 8 | } --------------------------------------------------------------------------------