MongoDB
Tags: cheatsheet, mongodb, nosql
Published: 2022-11-26 11:20:50

#### Reference
https://docs.mongodb.com/manual/reference/

## Default MongoDB Port
Default Port | Description
------------ | -----------
27017 | The default port for mongod and mongos instances. You can change this port with port or --port.
27018 | The default port for mongod when running with --shardsvr command-line option or the shardsvr value for the clusterRole setting in a configuration file.
27019 | The default port for mongod when running with --configsvr command-line option or the configsvr value for the clusterRole setting in a configuration file.

## Common Mongod options
``` bash
mongod --help
mongod --dbpath <directory path>
mongod --logpath <file path>
mongod --port <port number>
mongod --auth
mongod --bind_ip localhost,123.123.123.123
// Let Mongod run as Daemon
mongod --fork
mongod --replSet "<Replicate set name>"
mongod --keyFile "<Key file path>"
mongod --sslMode requireSSL
mongod --sslCAFile <CA file path in PEM format>
mongod --sslPEMKeyFile <Key file path in PEM format>
mongod --config "<Configuration file path>"
mongod -f "<Configuration file path>'
```

## Default Database Roles
Role | Privileges
---- | ----------
Database User | readAnyDatabase, readWriteAnyDatabase
Database Administration | dbAdminAnyDatabase,userAdminAnyDatabase
Cluster Administration | -
Backup/Restore | -
Super User | root
userAdmin | -
dbAdmin | -
dbOwner | -
readWrite | -

## Manage db user
``` bash
//
// Create a new user
//
mongo admin --host localhost:27000 --eval '
  db.createUser({
    user: "m103-admin",
    pwd: "m103-pass",
    roles: [
      {role: "root", db: "admin"}
    ]
  })
'

// OR

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

//
// Grant role to db user
//
db.grantRolesToUser( "dba",  [ { db: "playground", role: "dbOwner"  } ] )

//
// Query the role privileges
//
db.runCommand( { rolesInfo: { role: "dbOwner", db: "playground" }, showPrivileges: true} )
```

## MongoDB Shell (Common operations)
``` bash
# Connect to MongoDB server
mongo "mongodb+srv://cluster0.rwrtm.mongodb.net/<dbname>" --username test
// OR
mongo --username root --password root123 --authenticationDatabase admin

# Show all existing databases
show dbs
# or
show databases

# Switch database
use <database_name>

# Show all collection within current database
show collections

# Create a new collection
db.createCollection('<collection_name>');

# Create index
db.<collection>.createIndex(
  { "product": 1 },
  { "name": "name_index" }
)

# Load data into database
load('loadMovieDetailsDataset.js')

# Shutdown the Mongod (*Must switch to 'admin' database first)
db.shutdownServer()
// OR
db.adminCommand( { shutdown: 1 } )

# Iterate next result set in cursor
it

# Select document
## Select all data with pretty print out
db.<collection_name>.find().pretty()
## Select with matching criteria for array or nested object
db.movieDetails.find({ "genres.1": "Western" })
## Projection: Select the 'genres' field in return only (1: include, 0: exclude)
db.movieDetails.find({ "year": 1982 }, { "genres": 1 })
## With comparison operators ($eq, $gt, $gte, $in, $lt, $lte, $ne, $nin)
db.movieDetails.find({ writers: { $in: [ 'Ethan Coen', 'Joel Coen' ]}})
## With element operators ($exists, $type)
db.movies.find({ viewerRating: { $type: 'int'}})
## With logical operators ($and, $not, $nor, $or)
db.shipwracks.find({$or: [{watlev: {$eq: 'always dry'}}, {$and: [{depth: {$type: 'int'}}, {depth: {$eq: 0}}]}]})
## With array operator ($all, $elemMatch, $size)
db.movieDetails({genres: {$all: ["Comedy", "Crime", "Drama"]}})
## WIth evaluation operators ($expr, $jsonSchema, $mod, $regex, $text, $where)
db.movieDetails({'awards.text': {$regex: /^Won .*/}})

# Insert document
## Insert only one document
db.<collection_name>.insertOne({});
## Insert few documents at a time
db.<collection_name>.insertMany([],{ "ordered": <boolean> });

# Update document
# Update only one document
db.moviesScratch.updateOne({"type": "movie"}, { $set: { "type": "book" } })
## Update few documents at a time
db.moviesScratch.updateMany({}, { $set: { "star": "" } })
## Update or Insert a new document if not existed
db.moviesScratch.updateOne({ title: "Steve Jobs" }, { $set: { title: "Steve Jobs", year: 2000, type: "movie", comment: [] }}, { upsert: true })
# Replace whole document (field '_id' is immutable and can't be changed)
db.moviesScratch.replaceOne({title:"Steve Jobs"}, tmp)

# Delete document
## Delete only one document
db.moviesScratch.deleteOne({title:"Steve Jobs 2"})
## Delete few documents at a time
db.moviesScratch.deleteMany({title:"Steve Jobs"})
```

## User management commands:
``` bash
db.createUser()
db.dropUser()
```

# Collection management commands:
``` bash
db.<collection>.renameCollection()
db.<collection>.createIndex()
db.<collection>.drop()
```

# Database management commands:
``` bash
db.dropDatabase()
db.createCollection()
```

# Database status command:
``` bash
db.serverStatus()
```

# Log related command:
``` bash
# Get the logging components:
db.getLogComponents()

# Change the logging level:
db.setLogLevel(0, "index")

# View the logs through the Mongo shell:
db.adminCommand({ "getLog": "global" })
```

# Profile related command:
``` bash
# Get profiling level
db.getProfilingLevel()

# Set profiling level:
db.setProfilingLevel(1)

# Set slowms to 0:
db.setProfilingLevel( 1, { slowms: 0 } )

# Get profiling data from system.profile:
db.system.profile.find().pretty()
```

# Built-in management tools
Program | Description | Usage
------- | ----------- | -----
mongostat | Get stats on a running mongod process. | mongostat --port 30000
mongodump | Get a BSON dump of a MongoDB collection. | mongodump --port 30000 --db applicationData --collection products
mongorestore | Restore a MongoDB collection from a BSON dump. | mongorestore --drop --port 30000 dump/
mongoexport | Export a MongoDB collection to JSON or CSV (or stdout!). | mongoexport --port 30000 --db applicationData --collection products -o products.json
mongoimport | Create a MongoDB collection from a JSON or CSV file. | mongoimport --port 30000 products.json

# Replication
- Log Format
  1. Binary
  2. Statement-Based
- Roles
  1. Primary
  2. Secondary
  3. Arbiter
  4. Delayed
- Commands

Command | Description
------- | -----------
rs.status() | Getting replica set status.
rs.initiate() | Initiating the replica set.
rs.add() | Adding other members to replica set.
rs.isMaster() | Getting an overview of the replica set topology.
rs.stepDown() | Stepping down the current primary.