MongoDB Basics Tutorial

In this MongoDB tutorial we learn about the command line and Mongo Shell, BSON (JSON-like) document structure and MongoDB's data types.


We’re using Windows for this course. If you’re using MacOS or Linux your application paths may not look the same as ours. Simply replace ours with what is specific to your operating system and the commands will work.

The Command Line

The command line is simply the Command Prompt in Windows or the Terminal in MacOS and Linux.

Because we’re going to be working with both the command line and the MongoDB shell in this course, we thought it would be useful to quickly cover some essential commands for those who are unfamiliar with it.

We understand it seems a little frightening at first, specially for Windows users, but it’s really not.

When we write something in the command line, it’s known as a command and we can do almost anything with them.

Example:
systeminfo

Commands can have more than one word.

Example:
help convert

Commands can also have options, otherwise known as flags, such as --help . Flags are typically application specific and used when starting an application.

An option can have a value, which we specify after the option.

Syntax:
--option value

If the value requires a string, we have to wrap the value in quotes.

Syntax:
--option "option value"

MongoDB use these options when we start its processes. Let’s consider the following example.

Example:
mongod --configsvr --replSet ConfigReplSet --bind_ip localhost:27019
  1. First, we start the mongod.exe file with the mongod command.
  2. Then, we specify that we want this server instance to be a config server with the --configsvr option.
  3. Next, we tell the MongoDb that we want to use ‘ConfigReplSet’ as the configuration replica set with the --replSet option.
  4. Finally, we bind the server instance to the localhost IP (127.0.0.1) with the port number 27019 with the --bind_ip option. Any database instance will have to connect through that host:port.

Let’s look at some operating system specifics.

Windows Command Prompt

In Windows we have two options to start the Command Prompt: with or without administrator privileges.

In this course we will only need admin privileges when creating new directories on our system, as we saw in the Environment Setup lesson .

To open the Command Prompt, click on the Windows or Search button and type ‘cmd’.

  • To run the Command Prompt without admin privileges simply hit Enter on you keyboard or click on the icon.
  • To run the Command Prompt with admin privileges select the Run as administrator. If the option doesn’t show, simply right-click the icon and select the option from the flyout menu.

The table below lists some common commands that we’ll use in this course.

CommandDescriptionUsage
helpProvides a list of available commandshelp
Provides more details about the specified commandhelp command
dirDisplay the contents of the current directorydir
Dislpay the contents of the specified directorydir folder_name
cdDisplay the name of the current directorycd
Change to the following directorycd folder_path
Go up one directorycd ..
Go up more than one directorycd ../../.. etc.
mdCreate a new directory (folder)md folder_name
This command requires admin privileges
Create nested directoriesmd folder_name/sub-folder_name
rmDelete an empty directoryrm folder_name
Delete a directory with contentsrm /s folder_name
clsClear the screen visuallycls
It doesn’t affect any previous commands
exitClose the current Command Prompt windowexit

When we’re in the MongoDB Shell (MongoDB’s command line) we can use Ctrl+C to stop and exit out of it.

MacOS Terminal

Unix systems like MacOS doesn’t have to be started with admin privileges. Instead, the commands themselves use the sudo keyword to specify admin privileges.

In this course we will only need admin privileges when creating new directories on our system, as we saw in the Environment Setup lesson.

There are two ways to open the terminal on MacOS:

  • Click the Launchpad icon in the Dock, type ‘terminal’ in the search field, then click Terminal.
  • In the Finder, open the /Applications/Utilities folder, then double-click Terminal.

The table below lists some common commands that we’ll use in this course.

CommandDescriptionUsage
-hProvides more details about the specified commandcommand -h
manProvides a manual for the specified commandman command
lsDisplay the contents of the current directoryls
pwdDisplay the name of the current directorypwd
cdChange to the Home directorycd or cd ~
Change to the following directorycd folder_path
Go up one directorycd ..
Go up more than one directorycd ../../.. etc.
sudoRun command with super user security privilegessudo command
mkdirCreate a new directory (folder)mkdir folder_name
Create nested directoriesmkdir -p folder_name/sub-folder_name
rmdirDelete an empty directoryrmdir folder_name
rmDelete a directory with contentsrm -R folder_name
clearClear the screen visuallyclear
It doesn’t affect any previous commands
exitClose the current Terminal windowexit

When we’re in the MongoDB Shell (MongoDB’s command line) we can use Ctrl+C to stop and exit out of it.

Linux Terminal

Unix systems like Linux doesn’t have to be started with admin privileges. Instead, the commands themselves use the sudo keyword to specify admin privileges.

In this course we will only need admin privileges when creating new directories on our system, as we saw in the Environment Setup lesson.

There are multiple ways to open the terminal in Linux, below are the most common.

  • Press Ctrl+Alt+T
  • Press Alt+F2, type in ‘gnome-terminal’ and press Enter.
  • Press the super key (aka Windows key). You should see the Terminal application listed on the left-hand side application pane. If you don’t see it listed, simply start searching for ‘Terminal’ in the search area.

Different Linux flavours may have different methods of getting into the terminal. For example, Ubuntu allows Ctrl+Alt+T, but in CentOS you will need to explicitly create that shortcut. Simply use your favorite online search engine to find your OS’s method.

The table below lists some common commands that we’ll use in this course.

CommandDescriptionUsage
-helpProvides more details about the specified commandcommand -help
manProvides a manual for the specified commandman command
lsDisplay the contents of the current directoryls
pwdDisplay the name of the current directorypwd
cdChange to the Home directorycd or cd ~
Change to the following directorycd folder_path
Go up one directorycd ..
Go up more than one directorycd ../../.. etc.
sudoRun command with super user security privilegessudo command
mkdirCreate a new directory (folder)mkdir folder_name
Create nested directoriesmkdir -p folder_name/sub-folder_name
rmdirDelete an empty directoryrmdir folder_name
rmDelete a directory with contentsrm -R folder_name
clearClear the screen visuallyclear
It doesn’t affect any previous commands
exitClose the current Terminal windowexit

When we’re in the MongoDB Shell (MongoDB’s command line) we can use Ctrl+C to stop and exit out of it.

Mongo Shell

The Mongo Shell is a Javascript shell that we use to interact with MongoDB.

We will cover many of the commands you need throughout the course, but here are some basics.

Because mongo is just a Javascript shell, we can simply look up Javascript documentation online or for MongoDB-specific functionality, we can use the help command.

Output:
db.help()                    help on db methods
db.mycoll.help()             help on collection methods
sh.help()                    sharding helpers
...

show dbs                     show database names
show collections             show collections in current database
show users                   show users in current database
...

As we can see from the output, different levels of help are available by using methods.

A method, also known as a function, is a section of logic wrapped in a convenient container. As an example, let’s consider a simple update command.

Example:
db.collection.updateOne()

We can use this method to update a document with new values. We don’t have to go through the whole low-level process or even have to know how it updates, we simply pass in arguments and the method logic does the rest.

Methods can receive arguments if they have parameters specified in the parameter list between the parentheses.

An argument is simply a value that is specific to the method and is used by the logic inside to perform the operations it needs.

As an example, let’s consider our update command again.

If we just run the command without arguments, nothing will happen because how does the method know what we want to update.

We need to pass in the values we want to update as arguments. If we need to pass in multiple arguments, we simply separate them with a comma operator.

Syntax:
db.collection.method(argument_1, argument_2)

Let’s look at the .updateOne() method’s arguments

Example:
db.users.updateOne(
    { "name" : "John" },
    {
        $set : { "name" : "Jack" }
    }
)

In the example above, we passed two arguments to the method. Don’t worry about the curly braces and $ operators at the moment.

  • In the first argument we’re looking for a document that has the ‘name’ field set as ‘John’. Thats the one we want to update with a new value.
  • In the second argument we specify the change we want to make. We set the value of the ‘name’ field to ‘Jack’.

Arguments can also be optional. That means we don’t need to pass in a value for it, it will use whatever is set as its default.

The MongoDB official documentation shows when a value is optional for a method.

We can see what a method is doing if we run it without parentheses. This will print the Javascript source code for the method.

It’s great if you cannot remember the parameters and don’t want to visit the documentation, or if you’re just curious to see how it works.

Example:
db.users.updateOne
Output:
function (filter, update, options) {
    var opts = Object.extend({}, options || {});

    // Check if first key in update statement contains a $
    var keys = Object.keys(update);
    if (keys.length == 0) {
        throw new Error("the update operation document must contain at
        least one atomic operator");
    ...

In addition to using the shell interactively, we can also pass the shell JavaScript files to execute.

Example:
mongo script1.js script2.js
Output:
loading file: script1.js
I am script1
loading file: script2.js
I am script2

The shell will execute each script and exit.

There is a lot more we can learn about the shell, but we’ll go into that as necessary.

BSON (JSON-like)

MongoDB uses a JSON-like syntax for its documents called BSON, or Binary JSON.

For those who are unfamiliar with JSON, let’s see some quick examples.

key:value Pairs

JSON uses key:value pairs for its data, where a key is associated with a value by using the colon : operator.

Keys are also known, perhaps more commonly in MongoDB, as fields.

Example:
key : value

The value can be any of the MongoDB data types as well as arrays.

Multiple key:value pairs in the same scope are separated with a comma.

Example:
key_1 : value_1,
key_2 : value_2,
...

A practical example would look like the following.

Example:
"name" : "John",
"name" : "Jane"

Arrays

An array allows us to store multiple values in a single container. Arrays are wrapped in open and close square brackets [ ] and its values are separated with a comma.

Example:
key : value,
key : [array_value_1, array_value_2, ...]

Arrays may contain multiple key:value pairs for each of its values as long as they are scoped correctly with curly braces.

Example:
key : value,
key : [
    { array_value_1_sub-key_1 : array_value_1_sub-value_1, array_value_1_sub-key_2 : array_value_1_sub-value_2 },
    { array_value_2_sub-key_1 : array_value_2_sub-value_1, array_value_2_sub-key_2 : array_value_2_sub-value_2 },
    ...
]

A practical example would look like the following.

Example:
"students":[
    { "name" : "John", "age":"33" },
    { "name" : "Jane", "age":"28" },
    { "name" : "Jack", "age":"32" },
    { "name" : "Jill", "age":"27" }
]

Scope

JSON uses open and close curly braces { } to define scope.

Example:
{
    // everything inside these two
    // curly braces are in its scope
}

We are allowed to nest pairs inside others with nested scope, as seen above with the arrays example.

Example:
{
    // everything inside these two
    // curly braces are in its scope

    {
        // this is nested scope
    }
}

Pairs must always be in at least one scope. A practical example would look like the following.

Example:
{
    "name" : "School of hard knocks",
    "students" : [
        { "name" : "John", "age":"33" },
        { "name" : "Jane", "age":"28" },
        { "name" : "Jack", "age":"32" },
        { "name" : "Jill", "age":"27" }
    ]
}

Each document in MongoDb will consist of data that looks like this.

As an example, consider a blog. A single post might look something like the following.

Example:
{
    "title":        "How to Mongo",
    "description":  "Learn how to Mongo",
    "author":       "John Doe",
    "url":          "/how-to-mongo/",
    "tags":         ["MongoDB", "Database", "Learn"],
    "likes":        10,
    "rating":       [{ "score": 6 }, { "score": 7 }],
    "comments":
    [{
        "user":     "Jane",
        "comment":  "Thanks for the toot",
        "timestamp":"2020-11-09",
        "likes":    4
    },
    {
        "user":     "Jack",
        "comment":  "You forgot DB at the end",
        "timestamp":"2020-11-10",
        "likes":    3
    }]
}

For the sake of simplicity, we add the dates in the example above as a string instead of using a dedicated function.

You may have noticed that all the fields (keys) in our example are wrapped in quotes. While technically not necessary, it is a JSON convention and one we will follow throughout this course.

Data Types

MongoDB allows us to use any of the following data types within our database.

Data TypeDescription
ArrayThis data type can store multiple values in a single key.
BinaryThis data type can store binary data.
BooleanThis data type can store boolean values like true (1) or false (0).
CodeThis data type can store Javascript code into the document.
DateThis data type is the date and/or time in Unix time format.
DoubleThis data type can store floating point numerical values like 3.14.
IntegerThis data type can store whole numeric values. The value can 32-bit or 64-bit depending on the architecture of your server.
Min/Max KeysThis data type can compare a value against the lowest or highest elements.
NullThis data type can store null values. A null value is the absense of a value.
ObjectThis data type is used for embedded documents.
Regular expressionThis data type is used to store regular expressions .
StringThis data type can store valid UTF 8 characters, words, sentences, numbers etc. which must be wrapped in quotes. It’s the most used data type in MongoDB.
SymbolThis data type is typically used for languages that use a specific type.
Example:
db.createCollection("collection_name")

Note that while the boolean values true and false technically represent 1 and 0 respectively, we always use the actual keywords because ordering in MongoDB is done with numbers like 1.