This is an old revision of the document!


MongoDB


Basics

Runs on port: 27017


Create DB

use db_name # if db_name doesn't exist it will create it

Create user

# first user
use admin
> db.createUser(
... {
... user: "kalenpw",
... pwd: passwordPrompt(),
... roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
... }
... )
 
# user for specific database
use db_name
> db.createUser(
... {
... user: "kalenpw",
... pwd: passwordPrompt(),
... roles: [
... { role: "readWrite", db: "locallibrary" }
... ]
... }
... )

Installation

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

Query

// Find all
db.authors.find(); // can also pass blank filter {}
// find filter
db.authors.find({'first_name': 'Bob'}); // IS case sensitive
 
// count occurences
db.authors.countDocuments({}) // requires empty filter