MongoDB
These notes are based on the NetNinja tutorial series on YouTube: https://www.youtube.com/playlist?list=PL4cUxeGkcC9h77dJ-QJlwGlZlTd4ecZOA
SQL vs No SQL databases
- SQL uses tables and rows
- No SQL uses collections and documents
- No SQL documents are very much like JSON and objects in Javascript
- No SQL documents can contain a document inside them
MongoDB Docker Image
- To create a MongoDB Docker image, add a
docker-compose.ymlfile and add the following content:
services:
mongodb:
image: mongo:latest
container_name: mongodb_sample_project
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: rootpassword
ports:
- 27017:27017
volumes:
- mongodb_data:/data/db
volumes:
mongodb_data:
driver: local
- To run the container, type
docker-compose up -d
MongoDB Compass
MongoDB Compass is a GUI for interacting with MongoDB locally.
- Install the MongoDB Compass from https://www.mongodb.com/try/download/shell
- Enter this URL to access MongoDB:
mongodb://<username>:<password>@localhost:27017/?authSource=admin
Commands:
helpreturns list of commandsexitexits the mongo shellshow dbsreturns a list of all databasesuse <db_name>switch to a different database (DB doesn't necessarily need to exist)clsclears the terminal windowshow collectionsreturns a list of all collection in the current database
MongoDB Shell
Mongosh is an interactive shell for working with MongoDB locally.
- Install
mongoshthrough homebrew:brew install mongosh - Run the shell with this command:
mongosh admin -u <username> -p <password>
General Notes
- MongoDB stores documents as BJSON which stands for binary JSON.
- A value in a document can be another document (nested documents).