MongoDB Basics in 5 Minutes
This article is intended for beginners who want to quickly learn the basics of working in MongoDB without getting into the documentation and tutorials on YouTube.
Join the DZone community and get the full member experience.
Join For FreeMongoDB is a document-oriented database management system that does not require any predefined schema.
It is considered one of the classic examples of NoSQL systems. It uses JSON-like documents and a database schema. The database is used in web development, in particular, within the framework of some JavaScript stacks such as MEAN, MEVN, MERN, which are often used by web developers as their favorite tech stacks for creating applications.
Installation
You can download MongoDB from the official website for Linux, macOS, and Windows. In Linux, you can also do it with one of the following commands:
apt
sudo apt install -y mongodb
dnf
cat <<EOF | sudo tee /etc/yum.repos.d/mongodb.repo
[mongodb-org-4.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/4.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc
EOF
sudo yum install -y mongodb-org
brew
brew tap mongodb/brew
brew install mongodb-community
Also, to interact with the database, we need a shell (MongoShell), which can be downloaded separately from here.
Basics
After successfully installing MongoDB and Mongoshell, we can finally start interacting with the database using the terminal. You just need to enter mongosh:
As you can see, we are in the test database, but in fact, it does not exist yet!
Here are more details about what will be written below.
The thing is that there is no database in MongoDB until we insert something into it. Also, when referring to certain MongoDB objects (database, collection), they change their values only if they exist, and if they do not exist, they are simply created. Let’s demonstrate how it works:
show dbs
The show DBS command shows what databases currently exist. As you can see, there is no test value in the list.
To create a new database (or use an existing one) we must use the use keyword:
use new_database
As you can see, we move to the new_database database, but we do not see it in the list (this is due to the rule that I’ve mentioned above: a database does not exist until we insert something into it).
Let’s create a new collection called customers and insert the name: Alexey into it:
db.customers.insertOne({name: "Alexey"});
So, we access the database using DB, then we specify the collection separated by a dot and insert the value using the insertOne()function. JavaScript is the MongoDB query language. MongoDB relies on MozJs, which is a fork of SpiderMonkey (Mozilla Firefox). If you’re interested, please take a look at the source code.
Now let’s see what collections our database has. But how can we do it? We can enter DB. and press Tab to see what properties and methods our DB object has (for ease of understanding, you can consider an ordinary object from JavaScript; there are even similar methods: toString, isPrototypeOf, hasOwnProperty).
Next, we can view our collections using the special getCollectionNames method:
db.getCollectionNames();
Voila! We have an array of our collections and we can use the same principle (finding the methods we need) to explore the whole MongoDB, but I still have something to tell you. So, let’s continue.
There are command abbreviations that we can also use, for example, show collections will return the same, but this will look more readable:
show collections
Our collection, by the way, also has methods and properties, but they are slightly different:
We can use the find() method to display the entire contents of the collection:
db.customers.find();
Let’s add a few more customers using the insertMany()method:
db.customers.insertMany([{name: "Jinx"}, {name: "Tony"}, {name: "Poul"}]);
So, let’s notice a few things in the screenshot:
The insertMany()method takes an array of elements, not just elements.
MongoDB doesn’t care if there is a space between a bracket and a key or its value.
MongoDB syntax is very similar to JavaScript syntax, so we can use all types of quotes (double, single, and backticks).
In response, this method gives us an object that has the acknowledged property (more details here) and a nested object with keys from the array and corresponding id. Now let’s display two users (no matter which) from our list using the following command db.customers.find().limit(2):
As you can see, we have displayed only two objects from our collection. But what else can we do with the “found” objects? Here’s what:
The method has its own methods and, just like in JavaScript, we can chain methods to get the result that calls one method from another method separated by a dot.
Now, let’s sort our values using the sort() method:
The sort() method takes an object indicating by what value to sort as an argument. 1 means that sorting needs to be done in ascending order, while -1 implies sorting in descending order.
You can sort values using two arguments as well, but first, let’s add them! To add values to the element found in the collection, let’s use the updateOne function:
db.customers.updateOne({name: "Alexey"}, {$set: {age: 29}});
The unusual keyword $set you can see in the screenshot is an atomic operator. We’ll talk about it later. The main thing you need to see now is that we have changed the value, and the $set simply indicates the new values in our record.
Now let’s use the updateMany() method to change the values of a set of elements, and then move on to sorting with two arguments:
db.customers.updateMany({name: {$ne: "Alexey"}}, {$set: {age: 15}});
There is one more atomic operator that denotes not equal. In this case, the query sounds like this: “Find all the records where the name is not equal to ‘Alexey’ and set the ‘age’ value to 15”.
Now let’s sort the array using two arguments:
db.customers.find().sort({age: -1, name: -1});
Here sort() takes an object with two keys as an argument. First, it will sort the records by the first key, and if it finds duplicate first keys, it will start sorting by the second key. -1 means reverse sorting (in descending order).
MongoDB allows you to get specific fields from found objects and not to show other fields (that we don’t need):
db.customers.find({}, {name: 1, _id: 0});
Here we just use all our records with {} (since there is no specific identifier for finding, MongoDB returns all the records), and we pass what we want to see as the second argument. 1 corresponds to what will be displayed, and 0 is, on the contrary, the data that will not be displayed.
We can display our values using other methods, but the child methods will also be different:
db.customers.aggregate();
db.customers.aggregate().toArray();
In this case, we have converted our data array into a regular array. Later we will be able to perform some operations on it.
More Complex Queries
Atomic operators are needed to complicate queries. Popular atomic operators are:
- gt – greater than
- lt – less than
- gte and lte – greater than or equal and less than or equal
- eq – equal
- ne – not equal
- in – the value is contained in something
- nin – the value is not contained in something
- or – or
- and – and
- exists – exists
- set – change or add
We will consider some of them below:
db.customers.find({age: {$gt: 15}});
As you can see, all the records with an age field greater than 15 are displayed.
db.customers.find({name: {$in: ['Alexey', 'Jinx']}});
All the records whose name is contained in the array ['Alexey', 'Jinx'] are also displayed.
Let’s add one more object that does not have the age field and check the functionality of the exists operator:
db.customers.find({age: {$exists: true}});
We see that exists works correctly and the record with the name: 'Denis' is not displayed.
It is worth clarifying that atomic operators can work with almost all commands in MongoDB. What’s more, you can combine them and create complex queries.
All other commands like:
- deleteOne (deletes a record)
- replaceOne (replaces a record)
- updateOne (updates a record)
And their twin brothers with Many work the same way.
You can try to find out why they are needed simply by creating a database with a couple of records and making some experiments (this will help you quickly learn the material and remember it for a long time). After all, you already know everything you need.
Opinions expressed by DZone contributors are their own.
Comments