MongoDB Management

Create a new database

use {databases-name}

Check current database

db

Show database

show dbs

The empty database won’t be displayed (at least one document is inserted)

In MongoDB default database is test. If you didn’t create any database, then collections will be stored in test database.

Drop database

db.dropDatabase()

Collections

Create a collection

db.createCollection("a-collection")

Show collections

show collections

Mongodb create a collection automatically when insert a document.

Drop collection

db.mycollection.drop()

Backup

mongodump -d {database-name} -o {dump-pass}

Restore for bson

mongorestore -d {database-name} -c {collection-name} {dump-pass}/{collection-name}.bson

MongoDB Mac Config

Install MongoDb from HomeBrew

brew install mongodb

Create the default data folder and change permission

sudo mkdir -p /data/db/

Start MongoDb service

brew services start mongodb

Setup authentication

Go to the console

mongo

use admin

// create root
db.createUser(
  {
    user: "root",
    pwd: "a-password",
    roles: [ "root" ]
  }
)

// create admin user
db.createUser(
  {
    user: "admin",
    pwd: "a-password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

// verify the username and the password
db.auth("admin", "a-password")

Create a database user

use admin

db.createUser(
   {
     user: "dbUser",
     pwd: "a-password",
     roles:
       [{ role: "readWrite", db: "dbUser" }]
   }
)

// verify the username and the password
db.auth("dbUser", "a-password")

Adding following in

/usr/local/etc/mongod.conf

security:
  authorization: enabled

Restart MongoDB

brew services restart mongodb