MongoDB
Getting Started
Installing MongoDB
On Mac OS
brew tap mongodb/brew
brew install mongodb-community
On Ubuntu
# Install GPG as a pre-requisite step
sudo apt-get install gnupg
# Add MongoDB's public GPG key to the `apt` program
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -
# Add the MongoDB repository to the `apt` program's 'sources.list.d' directory
print "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
# Update `apt` to register these changes
sudo apt-get update
# Install the latest version
sudo apt-get install -y mongodb-org
Launching MongoDB
On Ubuntu
sudo systemctl start mongod
Stopping MongoDB
On Ubuntu
sudo systemctl stop mongod
Restarting MongoDB
On Ubuntu
sudo systemctl restart mongod
Setting up MongoDB to run on startup
On macOS
brew services start mongodb/brew/mongodb-community
On Ubuntu
sudo systemctl enable mongod
The config file is located at /usr/local/etc/mongod.conf
The config file is located at /etc/mongodb.conf
Configuring MongoDB
MongoDB config files are written in YAML, an example mongodb.conf file is provided below
Connecting to a MongoDB Atlas Server
# Using a single URI
mongo mongodb+srv://tommy:fighton@cluster-name.mongodb.net/dbname
# Using a URI and two flags
# Short Form
mongo 'mongodb+srv://cluster-name.mongodb.net/dbname' -u 'tommy' -p 'fighton'
# Long Form
mongo 'mongodb+srv://cluster-name.mongodb.net/dbname' --username 'tommy' --password 'fighton'
The MongoDB Shell
Databases
Basic Operations in the Shell
There are 4 basic operations
- Create
- Read
- Update
- Delete
Create
Use the insert function to add a document to a collection.
Documents can be represented in JavaScript Object Notation JSON and then inserted, which helps add simplicity.
Delete