DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Tracking Changes in MongoDB With Scala and Akka
  • Using AUTHID Parameter in Oracle PL/SQL
  • A Developer's Guide to Database Sharding With MongoDB
  • Kafka Link: Ingesting Data From MongoDB to Capella Columnar

Trending

  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • Top Book Picks for Site Reliability Engineers
  • How Trustworthy Is Big Data?
  1. DZone
  2. Data Engineering
  3. Databases
  4. MongoDB Basics in 5 Minutes

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.

By 
Alexey Shepelev user avatar
Alexey Shepelev
DZone Core CORE ·
Dec. 12, 21 · Tutorial
Likes (19)
Comment
Save
Tweet
Share
14.0K Views

Join the DZone community and get the full member experience.

Join For Free

MongoDB 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

Shell
 
sudo apt install -y mongodb


dnf

Shell
 
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

Shell
 
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:

Screenshot - 1

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:

Shell
 
show dbs


Screenshot - 2

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:

Shell
 
use new_database

Screenshot - 3

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:

Shell
 
db.customers.insertOne({name: "Alexey"});


Screenshot - 4

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

Screenshot - 5

Next, we can view our collections using the special getCollectionNames method:

Shell
 
db.getCollectionNames();


Screenshot - 6

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:

Shell
 
show collections


Screenshot - 7

Our collection, by the way, also has methods and properties, but they are slightly different:

Screenshot - 8

We can use the find() method to display the entire contents of the collection:

Shell
 
db.customers.find();


Screenshot - 9

Let’s add a few more customers using the insertMany()method:

Shell
 
db.customers.insertMany([{name: "Jinx"}, {name: "Tony"}, {name: "Poul"}]);


Screenshot - 10

So, let’s notice a few things in the screenshot:

  1. The insertMany()method takes an array of elements, not just elements.

  2. MongoDB doesn’t care if there is a space between a bracket and a key or its value.

  3. 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):

Screenshot - 11

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:

Screenshot - 12

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:

Screenshot - 13

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:

Shell
 
db.customers.updateOne({name: "Alexey"}, {$set: {age: 29}});

Screenshot - 14

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:

Shell
 
db.customers.updateMany({name: {$ne: "Alexey"}}, {$set: {age: 15}});


Screenshot - 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:

Shell
 
db.customers.find().sort({age: -1, name: -1});


Screenshot - 16

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

Shell
 
db.customers.find({}, {name: 1, _id: 0});


Sreenshot - 17

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:

Shell
 
db.customers.aggregate();
db.customers.aggregate().toArray();


Screenshot - 18

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:

Shell
 
db.customers.find({age: {$gt: 15}});


Screenshot - 19

As you can see, all the records with an age field greater than 15 are displayed.

Shell
 
db.customers.find({name: {$in: ['Alexey', 'Jinx']}});


Screenshot - 20

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:

Shell
 
db.customers.find({age: {$exists: true}});


Screenshot - 21

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.

MongoDB Database shell Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Tracking Changes in MongoDB With Scala and Akka
  • Using AUTHID Parameter in Oracle PL/SQL
  • A Developer's Guide to Database Sharding With MongoDB
  • Kafka Link: Ingesting Data From MongoDB to Capella Columnar

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!