Skip to content

Instantly share code, notes, and snippets.

@npodonnell
Last active January 8, 2024 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npodonnell/27c06763a1aa207b2a83d3722b0e19e5 to your computer and use it in GitHub Desktop.
Save npodonnell/27c06763a1aa207b2a83d3722b0e19e5 to your computer and use it in GitHub Desktop.
MongoDB Cheatsheet

MongoDB Cheatsheet

N. P. O'Donnell, 2021

Installing Community Edition (Ubuntu)

Check for latest version here

Add MongoDB repository to Apt and install:

MONGO_VERSION=4.4
curl -fsSL https://www.mongodb.org/static/pgp/server-$MONGO_VERSION.asc | sudo apt-key add -
  && echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/$MONGO_VERSION multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-$MONGO_VERSION.list
  && sudo apt update
  && sudo apt install mongodb-org

Enable and start the MongoDB service:

sudo systemctl enable mongod
sudo systemctl start mongod

Check if database is operational:

mongo --eval 'db.runCommand({ connectionStatus: 1 })'

Working in the Shell

Enter the MongoDB shell:

mongo

Security/User Management

First, create a user with a strong password:

> use admin
> db.createUser({user: "user", pwd: passwordPrompt(), roles: []})

Press Ctrl-C to exit the shell.

Edit the mongoDB configuration file (/etc/mongod.conf) and add the following under the security section:

security:
  authorization: enabled

Databases

List databases:

> show databases

Choose a database called foo. If foo doesn't exist MongoDB will create it once the first collection is created:

> use foo

Collections

Create a collection called bar:

> db.createCollection("bar")

Show collections in foo:

> show collections

Drop collection bar:

> db.bar.drop()

Create two more collections called customer and sale:

> db.createCollection("customer")
> db.createCollection("sale")

Insert two records into collection customer:

> db.customer.insert({"name": "alice", "likes": ["makeup", "clothes"]})
> db.customer.insert({"name": "bob", "likes": ["electronics", "sports"]})
> db.customer.insert({"name": "carol", "likes": ["video games"]})

List all the records in collection customer:

> db.customer.find()

List first record in collection customer (alice):

> db.customer.findOne()

List any records in collection customer whose name is bob:

> db.customer.find({name: "bob"})

Print how many records are in the customer collection:

> db.customer.count()

Delete carol from the collection customer:

> db.customer.remove({"name": "carol"})

Delete everything from the collection sale:

> db.sale.remove({})

Delete the customer and sale collections:

db.customer.drop()
db.sale.drop()

Indexes

Get indexes on customer collection:

> db.customer.getIndexes()

Create an ascending index on customer's age attribute:

> db.customer.createIndex({"age": 1})

Create an decending index on customer's age attribute:

> db.customer.createIndex({"age": -1})

Delete all indexes on customer collection:

> db.customer.dropIndexes()

Executing MongoDB Scripts

The mongoDB shell uses Javascript, and .js files may be piped into the shell:

mongo <database name> < <some .js file>

Example:

mongo mydb < generate-report.js

Step-by-Step Replica Set and Authentication

  1. On all nodes, delete all files in /var/lib/mongodb:
rm -fr /var/lib/mongodb/*
  1. Generate key-file on one node:
KEYFILE="/var/lib/mongodb/keyfile"
openssl rand -base64 16 > $KEYFILE
sudo chown root:root $KEYFILE
sudo chmod 400 $KEYFILE
  1. Copy key-file to the other nodes, same location.

  2. Edit /etc/mongod.conf and set the key-file, and authorization to disabled (for now):

security:
  keyFile: /var/lib/mongodb/keyfile
  authorization: disabled
storage:
  dbPath: /var/lib/mongodb
replication:
  replSetName: "rs"
  1. Restart mongod service.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment