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.
systeminfo
Commands can have more than one word.
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.
--option value
If the value requires a string, we have to wrap the value in quotes.
--option "option value"
MongoDB use these options when we start its processes. Let’s consider the following example.
mongod --configsvr --replSet ConfigReplSet --bind_ip localhost:27019
- First, we start the mongod.exe file with the mongod command.
- Then, we specify that we want this server instance to be a config server with the --configsvr option.
- Next, we tell the MongoDb that we want to use ‘ConfigReplSet’ as the configuration replica set with the --replSet option.
- 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.
Command | Description | Usage |
---|---|---|
help | Provides a list of available commands | help |
Provides more details about the specified command | help command | |
dir | Display the contents of the current directory | dir |
Dislpay the contents of the specified directory | dir folder_name | |
cd | Display the name of the current directory | cd |
Change to the following directory | cd folder_path | |
Go up one directory | cd .. | |
Go up more than one directory | cd ../../.. etc. | |
md | Create a new directory (folder) | md folder_name |
This command requires admin privileges | ||
Create nested directories | md folder_name/sub-folder_name | |
rm | Delete an empty directory | rm folder_name |
Delete a directory with contents | rm /s folder_name | |
cls | Clear the screen visually | cls |
It doesn’t affect any previous commands | ||
exit | Close the current Command Prompt window | exit |
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.
Command | Description | Usage |
---|---|---|
-h | Provides more details about the specified command | command -h |
man | Provides a manual for the specified command | man command |
ls | Display the contents of the current directory | ls |
pwd | Display the name of the current directory | pwd |
cd | Change to the Home directory | cd or cd ~ |
Change to the following directory | cd folder_path | |
Go up one directory | cd .. | |
Go up more than one directory | cd ../../.. etc. | |
sudo | Run command with super user security privileges | sudo command |
mkdir | Create a new directory (folder) | mkdir folder_name |
Create nested directories | mkdir -p folder_name/sub-folder_name | |
rmdir | Delete an empty directory | rmdir folder_name |
rm | Delete a directory with contents | rm -R folder_name |
clear | Clear the screen visually | clear |
It doesn’t affect any previous commands | ||
exit | Close the current Terminal window | exit |
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.
Command | Description | Usage |
---|---|---|
-help | Provides more details about the specified command | command -help |
man | Provides a manual for the specified command | man command |
ls | Display the contents of the current directory | ls |
pwd | Display the name of the current directory | pwd |
cd | Change to the Home directory | cd or cd ~ |
Change to the following directory | cd folder_path | |
Go up one directory | cd .. | |
Go up more than one directory | cd ../../.. etc. | |
sudo | Run command with super user security privileges | sudo command |
mkdir | Create a new directory (folder) | mkdir folder_name |
Create nested directories | mkdir -p folder_name/sub-folder_name | |
rmdir | Delete an empty directory | rmdir folder_name |
rm | Delete a directory with contents | rm -R folder_name |
clear | Clear the screen visually | clear |
It doesn’t affect any previous commands | ||
exit | Close the current Terminal window | exit |
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.
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.
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.
db.collection.method(argument_1, argument_2)
Let’s look at the .updateOne() method’s arguments
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.
db.users.updateOne
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.
mongo script1.js script2.js
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.
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.
key_1 : value_1,
key_2 : value_2,
...
A practical example would look like the following.
"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.
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.
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.
"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.
{
// 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.
{
// 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.
{
"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.
{
"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 Type | Description |
---|---|
Array | This data type can store multiple values in a single key. |
Binary | This data type can store binary data. |
Boolean | This data type can store boolean values like true (1) or false (0). |
Code | This data type can store Javascript code into the document. |
Date | This data type is the date and/or time in Unix time format. |
Double | This data type can store floating point numerical values like 3.14. |
Integer | This data type can store whole numeric values. The value can 32-bit or 64-bit depending on the architecture of your server. |
Min/Max Keys | This data type can compare a value against the lowest or highest elements. |
Null | This data type can store null values. A null value is the absense of a value. |
Object | This data type is used for embedded documents. |
Regular expression | This data type is used to store regular expressions . |
String | This 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. |
Symbol | This data type is typically used for languages that use a specific type. |
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.