Setup MongoDB - ChuanyuWang/test GitHub Wiki

MongoDB ChangeLog

All releases of MongoDB Community, refer to link
E.g. MongoDB 3.2 ChangeLog

Check compatibility of MongoDB Node.js drvier

https://docs.mongodb.com/drivers/node/current/compatibility/

How to install MongoDB on CentOS

Firstly, check the offical installation docs at link.

By default, MongoDB runs using the mongod user account and uses the following default directories:

  • /var/lib/mongo (the data directory)
  • /var/log/mongodb (the log directory)

If you installed via the package manager, The default directories are created, and the owner and group for these directories are set to mongod.

To use a data directory and/or log directory other than the default directories:

  1. Create the new directory or directories.
  2. Edit the the configuration file /etc/mongod.conf and modify the following fields accordingly:
    • storage.dbPath to specify a new data directory path (e.g. /some/data/directory)
    • systemLog.path to specify a new log file path (e.g. /some/log/directory/mongod.log)
  3. Ensure that the user running MongoDB has access to the directory or directories.
chown -R mongod:mongod <directory>

How to start/stop MongoDB service

sudo service mongod start
sudo service mongod stop
sudo service mongod restart
sudo service mongod status

You can verify that the mongod process has started successfully by checking the contents of the log file at /var/log/mongodb/mongod.log for a line reading

[initandlisten] waiting for connections on port <port>

where <port> is the port configured in /etc/mongod.conf, 27017 by default.

You can optionally ensure that MongoDB will start following a system reboot by issuing the following command:

sudo chkconfig mongod on

How to install MongoDB on Windows

Download MongoDB Community version, https://www.mongodb.com/try/download/community

Install MongoDB as service on Windows, refer to Start MongoDB Community Edition as a Windows Service

  • Create directories
mkdir c:\data\db
mkdir c:\data\log
  • Create a configuration file For example, create a file at C:\mongodb\mongod.cfg that specifies both systemLog.path and storage.dbPath:
systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db
  • Install the MongoDB service Run all of the following commands in Command Prompt with “Administrative Privileges”.
"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --config "C:\mongodb\mongod.cfg" --install
  • Remove the MongoDB service as needed
    To remove the MongoDB service use the following command:
    "C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --remove

Create the very first MongoDB user

Start MongoDB without access control. In the admin database, add a user with the userAdminAnyDatabase role.

Create the very first user admin which is used to create the other users. Execute mongo command:

use admin
db.createUser(
  {
    user: "admin",
    pwd: "pass",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
exit

Remember to exit and re-login with admin again before next operations.

Create MongoDB users

Re-start the MongoDB instance with access control as below. Add property authorization in mongod.cfg file

systemLog:
  destination: "file"
  path: "c:\\data\\log\\mongod.log"
storage:
  dbPath: "c:\\data\\db"
security:
  authorization: "enabled"

Create the 2nd user to actual read/write database.

use admin
db.auth("admin", "pass")
db.createUser(
  {
    user: "anotherUser",
    pwd: "pass",
    roles: []
  }
)

Role readWriteAnyDatabase provides the same read and write permissions as readWrite role, except it applies to all but the local and config databases in the cluster. To provide read and write privileges on local and config databases, additional role is required to be granted, see below.

use admin
db.auth("admin", "pass")
db.grantRolesToUser(
    "anotherUser",
    [
      { role: "readWrite", db: "config" },
      { role: "readWriteAnyDatabase", db: "admin" }
    ]
)

Check the roles are assigned correctly with below commands

> db.getUser("anotherUser")
{
    "_id": "admin.anotheruser",
    "user": "anotherUser",
    "db": "admin",
    "roles": [{
            "role": "readWrite",
            "db": "config"
        }, {
            "role": "mongostatRole",
            "db": "admin"
        }, {
            "role": "readWriteAnyDatabase",
            "db": "admin"
        }
    ]
}

The user been assigned role root is super user, who is able to do anything.

db.createUser({user:"root",pwd:"root",roles:["root"]})

MongoDB built-in roles

https://docs.mongodb.com/manual/reference/built-in-roles/

  • readWriteAnyDatabase

Provides the same privileges as readWrite on all databases except local and config. The role also provides the listDatabases action on the cluster as a whole.

Changed in version 3.4: Prior to 3.4, readWriteAnyDatabase includes local and config databases. To provide readWrite privileges on the local database, create a user in the admin database with readWrite role in the local database.

  • dbAdminAnyDatabase

Provides the same privileges as dbAdmin on all databases except local and config. The role also provides the listDatabases action on the cluster as a whole.

Changed in version 3.4: Prior to 3.4, dbAdminAnyDatabase includes local and config databases. To provide dbAdmin privileges on the local database, create a user in the admin database with dbAdmin role in the local database.

How to backup MongoDB

There are import/export tools from MongoDB v3.6.

Sample commands of mongodump in below

$mongodump
$mongodump --out /data/backup/
$mongodump --collection myCollection --db test
$mongodump --host mongodb.example.net --port 27017
$mongodump --host <host> --db <database> --username <user> --password <password> --out <path> --authenticationDatabase admin

Be careful before running mongodump command.

  • mongodump overwrites output files if they exist in the backup data folder.
  • The default output folder is the dump/ folder.
  • If you do not specify a database, mongodump copies all databases in this instance into the dump files.

How to restore MongoDB

Refer to https://docs.mongodb.com/v3.6/reference/program/mongorestore/#bin.mongorestore
E.g. Restore one database from a dump folder The path-to-folder specifies the dump directory which contains *.bson and *.json files belongs to one database.

mongorestore --username user --password pass --db database --dir <path-to-folder> --authenticationDatabase admin

How to run mongostat

use admin
db.createRole(
   {
     role: "mongostatRole",
     privileges: [
       { resource: { cluster: true }, actions: [ "serverStatus" ] }
     ],
     roles: []
   }
)
  • Grant a user with above role
use admin
db.grantRolesToUser(
    "dbUser",
    [
      { role: "mongostatRole", db: "admin" }
    ]
)
  • Run mongostat with above user
    $mongostat -h <host> -d <database> -u <user> -p <password> --authenticationDatabase admin

How to check storage engine of MongoDB

The serverStatus command output has a property serverStatus.storageEngine. It is a document with data about the current storage engine. The name property of this document tells the current storage engine.

> mongo
> db.version()
3.2.5
> use admin
switched to db admin
> db.auth("admin", "pass")
1
> db.serverStatus().storageEngine
{ "name" : "wiredTiger", "supportsCommittedReads" : true }

How to upgrade MongoDB from 3.2 to 3.6 in CentOS

Check the official documents before upgrading, and make sure MongoDB 3.2 is the latest patch, in my case, it's 3.2.22

Then follow the steps described in below:

Create /etc/yum.repos.d/mongodb-org-3.4.repo file with below content:

[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc

Check the available updates with command yum list mongodb-org, you will see below results:

Installed Packages
mongodb-org.x86_64                                            3.2.22-1.el7
Available Packages
mongodb-org.x86_64                                            3.4.24-1.el7

Stop running MongoDB service and update binary

service mongod stop
yum update mongodb-org

View FeatureCompatibilityVersion after upgrading MongoDB 3.4 with below command, and role clusterAdmin is required to view or set FeatureCompatibilityVersion.

> use admin
> db.grantRolesToUser( "admin", [{ role: "clusterAdmin", db: "admin" }] )
> db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )
{ "featureCompatibilityVersion" : "3.2", "ok" : 1 }
> db.adminCommand( { setFeatureCompatibilityVersion: "3.4" } )
{ "ok" : 1 }

Create a /etc/yum.repos.d/mongodb-org-3.6.repo file so that you can install MongoDB directly using yum:

[mongodb-org-3.6]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.6/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc

Check the available updates with command yum list mongodb-org, you will see below results:

Installed Packages
mongodb-org.x86_64                                            3.4.24-1.el7
Available Packages
mongodb-org.x86_64                                            3.6.23-1.el7

Stop running MongoDB service and update binary

service mongod stop
yum update mongodb-org

View FeatureCompatibilityVersion after upgrading MongoDB 3.6 with below command, and role clusterAdmin is required to view or set FeatureCompatibilityVersion.

> use admin
> db.grantRolesToUser( "admin", [{ role: "clusterAdmin", db: "admin" }] )
> db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )
{ "featureCompatibilityVersion" : "3.4", "ok" : 1 }
> db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } )
{ "ok" : 1 }

Start MongoDB with service mongod start.

⚠️ **GitHub.com Fallback** ⚠️