Install MongoDB on CentOS 7

How to install MongoDB on CentOS 7

This article explains how to install MongoDB on a CentOS 7 server.

Add MongoDB repository

vim /etc/yum.repos.d/mongodb-org-3.6.repo
[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

Update repository list

yum repolist

Install MongoDB

yum install -y mongodb-org

Start MongoDB service and enable after restart

systemctl start mongod
systemctl status mongod
systemctl enable mongod

Show logs

tail /var/log/mongodb/mongod.log

An output of waiting for a connection confirms that MongoDB has started successfully and we can access the database server with the MongoDB Shell:

mongo

To learn how to interact with MongoDB from the shell, you can review the output of the db.help() method which provides a list of methods for the db object.

> db.help()
DB methods:
	db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
	db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
	db.auth(username, password)
	db.cloneDatabase(fromhost)
	db.commandHelp(name) returns the help for the command
	db.copyDatabase(fromdb, todb, fromhost)
	db.createCollection(name, {size: ..., capped: ..., max: ...})
	db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
	db.createUser(userDocument)
	db.currentOp() displays currently executing operations in the db
	db.dropDatabase()
	db.eval() - deprecated
	db.fsyncLock() flush data to disk and lock server for backups
	db.fsyncUnlock() unlocks server following a db.fsyncLock()
	db.getCollection(cname) same as db['cname'] or db.cname
	db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
	db.getCollectionNames()
	db.getLastError() - just returns the err msg string
	db.getLastErrorObj() - return full status object
	db.getLogComponents()
	db.getMongo() get the server connection object
	db.getMongo().setSlaveOk() allow queries on a replication slave server
	db.getName()
	db.getPrevError()
	db.getProfilingLevel() - deprecated
	db.getProfilingStatus() - returns if profiling is on and slow threshold
	db.getReplicationInfo()
	db.getSiblingDB(name) get the db at the same server as this one
	db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
	db.hostInfo() get details about the server's host
	db.isMaster() check replica primary status
	db.killOp(opid) kills the current operation in the db
	db.listCommands() lists all the db commands
	db.loadServerScripts() loads all the scripts in db.system.js
	db.logout()
	db.printCollectionStats()
	db.printReplicationInfo()
	db.printShardingStatus()
	db.printSlaveReplicationInfo()
	db.dropUser(username)
	db.repairDatabase()
	db.resetError()
	db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into {cmdObj: 1}
	db.serverStatus()
	db.setLogLevel(level,<component>)
	db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
	db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
	db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
	db.setVerboseShell(flag) display extra information in shell output
	db.shutdownServer()
	db.stats()
	db.version() current version of the server
> use admin

switched to db admin

> db.createUser(
 {
    user: "admin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
 )

Successfully added user: {
	"user" : "admin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
vim /etc/mongod.conf
security:
  authorization: enabled

Restart MongoDB service

systemctl restart mongod

Inside MongoDB shell you now need to authorize:

db.auth('admin', 'password')

Quit the MongoDB shell with the exit command:

exit

MongoDB database files are located at /var/lib/mongo/ .

MongoDB log files are located at /var/log/mongo/ .

Create default ‘root’ user for MySQL

Recently, I had the issue that the MySQL ‘root’ user could not log into the data base:

shell> mysql -u root -p
Access denied for user 'root'@'localhost' (using password: YES)

The root cause was not that a wrong password was used or the user ‘root’ had no access rights. The root cause was that the user ‘root’ was not existing in the mysql.user table. In fact, the whole user table was empty. So the default ‘root’ user needs to be recreated again.

In order to log into MySQL without a user and password, MySQL needs to be restarted with the –skip-grant-tables  option.

shell> service mysqld stop
shell> /usr/bin/mysqld_safe --skip-grant-tables &

Then log into MySQL:

shell> mysql

The usual CREATE USER  command will not work here as this command would also set default permissions, however starting MySQL without grant tables will not allow you to set permissions. So the user ‘root’ needs to manually inserted into the mysql.user table, along with all privileges.

mysql> USE user;

mysql> INSERT INTO user (Host, User, Password) VALUES ('localhost','root','MyNewPass');
Query OK, 1 rows affected (0.04 sec)

mysql> UPDATE user SET Select_priv='Y',Insert_priv='Y',Update_priv='Y',Delete_priv='Y',Create_priv='Y',Drop_priv='Y',Reload_priv='Y',Shutdown_priv='Y',Process_priv='Y',File_priv='Y',Grant_priv='Y',References_priv='Y',Index_priv='Y',Alter_priv='Y',Show_db_priv='Y',Super_priv='Y',Create_tmp_table_priv='Y',Lock_tables_priv='Y',Execute_priv='Y',Repl_slave_priv='Y',Repl_client_priv='Y',Create_view_priv='Y',Show_view_priv='Y',Create_routine_priv='Y',Alter_routine_priv='Y',Create_user_priv='Y' WHERE user='root';
Query OK, 1 rows affected (0.03 sec)

Newer versions of MySQL might contain more privileges so make sure that all have been updated (all ‘*_priv’ columns contain a ‘Y’).

mysql> SELECT * FROM user WHERE user='root';

Then quit the database console, kill the mysqld_safe daemon, start the standard mysql daemon and retest it.

mysql> quit;
shell> killall mysqld_safe
shell> service mysqld start
shell> mysql -u root -p

The default ‘root’ user has now been restored and access with a password should be possible again!