Linux Server setup

Install MongoDB

In this chapter, we will install and set up the NoSQL database MongoDB.

The community version is free and probably sufficient for most projects.


Install MongoDB

We install the MongoDB database in several steps. I recommend checking the official site for the latest version.


__$ sudo apt-get update
__$ sudo apt-get install gnupg
__$ wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
__$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
__$ sudo apt-get install -y mongodb-org
 

Let's open the main configuration file of MongoDB with less.


__$ sudo less /etc/mongod.conf

/etc/mongod.conf


# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1


# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

In the output we can see:

  • Data: /var/lib/mongodb
  • Log file: /var/log/mongodb/mongod.log
  • Address: 127.0.0.1
  • Port: 27017

We can retrieve the version with --version:


__$ mongo --version


Uninstall MongoDB

How to uninstall MongoDB is described here only for the sake of completeness.

Stop MongoDB:


__$ sudo systemctl stop mongod
 

Uninstall MongoDB:


__$ sudo apt-get purge mongodb mongodb-clients mongodb-server mongodb-dev
__$ sudo apt-get purge mongodb-org*
__$ sudo apt-get autoremove
 

Delete MongoDB data and logs:


__$ sudo rm -r /var/lib/mongodb
__$ sudo rm -r /var/log/mongodb
 

Common MongoDB commands

Launch MongoDB:


__$ sudo systemctl start mongod

Stop MongoDB:


__$ sudo systemctl stop mongod

Restart MongoDB:


__$ sudo systemctl restart mongod

MongoDB status:


__$ sudo systemctl status mongod

MongoDB Shell via command line

Start MongoDB console:


__$ mongo

The MongoDB Shell:


MongoDB shell version v5.0.4
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2546fe7e-f27b-47c5-bde4-a486830256a9") }
MongoDB server version: 5.0.4
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
        https://community.mongodb.com
---
The server generated these startup warnings when booting:
        2022-01-03T12:53:35.053+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2022-01-03T12:53:36.787+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>

Show all databases:


__gt show databases;

Switch to the admin database:


__gt use admin;

Create a new user named admin with all privileges:


__gt db.createUser({
  user: "admin",
  pwd: "MyPassword",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
});

Create a new database:


__gt use MyDatabase;

A newly created database will not be displayed by show databases; as long as it is empty!

Insert a collection with a document:


__gt db.MyCollection.insert({ key: "val" });

List Collections:


__gt show collections;

List the contents of a collection:


__gt db.MyCollection.find().pretty();

pretty() is an addition to make the output more structured and readable.

Insert another document:


__gt db.MyCollection.insert({ key: "val2" });

Delete single document:


__gt db.MyCollection.deleteOne({ key: "val2" });

Output statistics of the current database:


__gt db.stats();

Delete Collection:


__gt db.MyCollection.drop();

Delete current database:


__gt db.dropDatabase();

Exit the MongoDB shell:


__gt exit