§8.5.

MongoDB

MongoDB is a modern “NoSQL” database management system. In this section, I explain how to install, initialize and use MongoDB.

Installation

To install MongoDB, follow the directions on the MongoDB website:

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

You can use homebrew to install:

$ brew tap mongodb/brew
...
$ brew install mongodb-community
...
$
Warning
MongoDB does not support the Windows Subsystem for Linux. For Windows development, you can install the Windows version of MongoDB or sign up for a cloud database service such as MongoDB Atlas.

Initializing and starting MongoDB

In production, MongoDB typically runs as a background service (or "daemon"). However, during development, I prefer to run it manually from the command line. Manually starting MongoDB gives me the flexibility to specify exactly where the database files are stored, and allows me to start and stop the server with ease.

To initialize a MongoDB database (i.e., to create an empty database file), simply create an empty directory using mkdir ./mdb:

$ mkdir ./mdb
$

It is possible to configure your system to run MongoDB as a service/daemon. I prefer to manually start the database by running mongod --dbpath ./mdb --bind_ip 127.0.0.1 directly:

$ mongod --dbpath ./mdb --bind_ip 127.0.0.1
[main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
[initandlisten] MongoDB starting : pid=3828 port=27017 dbpath=./mdb 64-bit host=benjamin
[initandlisten] db version v4.2.2
...
...
... <Lots of start-up information appears>
...
...
[initandlisten] waiting for connections on port 27017

You can stop the database management system by pressing Control+C.

Tip
The path ./mdb is used in these examples as the location of the internal data files used by MongoDB. A single MongoDB database server can host multiple databases. The internal data files store all of the databases. If the ./mdb directory is empty when the mongod command starts, the internal data files are automatically initialized. [1]

Interacting with the database shell

You can interact with the database by opening a new terminal and using the mongo command:

$ mongo
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("125b8541-1f26-465c-8864-4e0d4c63c720") }
MongoDB server version: 4.2.2
Server has startup warnings:
[initandlisten]
[initandlisten] WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
[initandlisten]          See http://dochub.mongodb.org/core/prodnotes-filesystem
[initandlisten]
[initandlisten] WARNING: Access control is not enabled for the database.
[initandlisten]          Read and write access to data and configuration is unrestricted.
[initandlisten]
---

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()
---

> use shoppingDB
switched to db shoppingDB
> db.items.insert({description: "Chocolate bar", quantity: 5});
WriteResult({ "nInserted" : 1 })
> db.items.insert({description: "Pasta", quantity: 1});
WriteResult({ "nInserted" : 1 })
> db.items.find()
{ "_id" : ObjectId("5e9eaa0f7c7cab835232e658"), "description" : "Chocolate bar", "quantity" : 5 }
{ "_id" : ObjectId("5e9eaa177c7cab835232e659"), "description" : "Pasta", "quantity" : 1 }
> db.getCollectionNames();
[ "items" ]
> db.items.drop();
true
> db.getCollectionNames();
[ ]
> exit
bye
$

In the transcript above, after starting mongodb, I switched to a database named shoppingDB with use shoppingDB. From there, I entered commands into MongoDB using the shell. Note that the MongoDB query language is JavaScript.

MongoDB does not require a schema. MongoDB creates the database shoppingDB when it is used (by the use command). Similarly, collections are created by inserting data. The function db.items.insert inserts a new object into the items collection in the shoppingDB database.

I then used db.items.find to search for elements in the items collection. Finally, I erased the entire collection with db.items.drop and confirmed the deletion of the collection by calling db.getCollectionNames.

These commands can also be saved to a text file. For example, I can create a file named shopping.js with the following contents:

b = new Mongo().getDB("shoppingDB");
db.items.insert({description: "Chocolate bar", quantity: 5});
db.items.insert({description: "Pasta", quantity: 1});
printjson(db.getCollectionNames());

cursor = db.items.find();
while (cursor.hasNext()) {
    printjson(cursor.next());
}

db.items.drop();

The script is executed from within the Mongo shell using the load function:

$ mongo
MongoDB shell version v4.2.2
...
> load("shopping.js")
[ "items" ]
{
	"_id" : ObjectId("5e9eaabf7c7cab835232e65a"),
	"description" : "Chocolate bar",
	"quantity" : 5
}
{
	"_id" : ObjectId("5e9eaabf7c7cab835232e65b"),
	"description" : "Pasta",
	"quantity" : 1
}
true
> exit
bye
$

Alternatively, run the script from the command line:

$ mongo shopping.js
...
[ "items" ]
{
	"_id" : ObjectId("5e9eaae631142a8f1b685493"),
	"description" : "Chocolate bar",
	"quantity" : 5
}
{
	"_id" : ObjectId("5e9eaae631142a8f1b685494"),
	"description" : "Pasta",
	"quantity" : 1
}
$

1. You can generate additional databases in the data files by issuing the use command from the mongo console (e.g., use shoppingDB to create a database named shoppingDB).