Skip to content
Studio 3T - The professional GUI, IDE and client for MongoDB
  • Tools
    • Aggregation Editor
    • IntelliShell
    • Visual Query Builder
    • Export Wizard
    • Import Wizard
    • Query Code
    • SQL Query
    • Connect
    • Schema Explorer
    • Compare
    • SQL ⇔ MongoDB Migration
    • Data Masking
    • Task Scheduler
    • Reschema
    • More Tools and Features
  • Solutions
  • Resources
    • Knowledge Base
    • MongoDB Tutorials & Courses
    • Tool/Feature Documentation
    • Blog
    • Community
    • Testimonials
    • Whitepapers
    • Reports
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Careers
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • Download
  • My 3T
search

Studio 3T® Knowledge Base

  • Documentation
  • Tutorials
  • Workshops
Take the fastest route to learning MongoDB. Cover the basics in two hours with MongoDB 101, no registration required.
Start the free course

Getting Started with MongoDB – An Introduction

Posted on: 07/05/2020 (last updated: 10/09/2021) by Kathryn Vargas

Let our Getting Started with MongoDB guide help you learn MongoDB, the most popular NoSQL database.

No introduction to MongoDB is complete without first looking at how it compares to SQL.

MongoDB vs SQL

Data organization

Instead of using tables, rows, and columns to establish relationships across data,

SQL uses tables, rows, and columns to organize data


Source: SQL Blog

MongoDB uses name-value pairs or fields, which then make up documents, which make up collections.

For a discussion of how relational schemas deal with name-value pairs, check this article.

MongoDB uses collections, documents, and key-value pairs to organize data

Source: MongoDB

Here’s a little cheat-sheet of how the database elements map to each other:

SQLMongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField

Check out Comparing MongoDB and SQL Concepts, the 4th lesson in Academy 3T’s free MongoDB course for beginners.

MongoDB has two clear main benefits over SQL when it comes to data organization:

  • Flexible and easy setup – Since a schema isn’t necessary upfront, getting started with MongoDB is quick and straightforward. You can dump unstructured data, query as you need, and worry about organizing your data later.
  • Speed – Because data is stored in name-value pairs, querying large volumes of data can be quite fast in MongoDB compared to relational databases – with the right indexes.

Data scaling

You naturally collect more data as your project or business grows, and there are two ways of addressing this growth: vertical or horizontal scaling.

  • Vertical scaling – Tethers you to a single server. As you deal with more data, you can add more storage space or upgrade to a more powerful CPU with higher RAM capacity to handle the workload, but you’re stuck with a server that might eventually prove inadequate for your current use case, or future use cases.
  • Horizontal scaling – Spreads out the load over multiple servers instead of relying on a single high-speed, high capacity server.

MongoDB uses a form of horizontal scaling called sharding. It divides the data into different shards, so that each shard only contains a subset of the data. If you need more capacity, you can easily add more as you go.

When it comes to data scaling, MongoDB provides two obvious benefits:

  • High scalability – You can distribute large volumes of data across multiple machines, and only add servers as needed.
  • High availability – This is done in MongoDB through replica sets, or groups of mongod processes that maintain the same data sets. If a whole shard comes down, you are not going to be able to access the part of your data stored in it. However, if one or several nodes of the replica set of a sharded cluster comes down, you will still be able to access your data. Note that you can still set up a shard without implementing any replica set, with only one server.

Query language

SQL has Structured Query Language; MongoDB has the MongoDB Query Language. Sometimes referred to as MQL, it uses BSON (Binary JSON), which is based on JSON (JavaScript Object Notation).

If you’re proficient in JavaScript, you’ll crush it in the mongo shell, MongoDB’s interactive JavaScript interface. MongoDB commands can get clunky pretty quickly however, so features like query autocompletion can be a real time-saver.

Don't know the mongo shell language? Use a MongoDB query builder and building your queries via drag-and-drop

If you aren’t proficient in JavaScript but want to learn MongoDB, features like a drag-and-drop MongoDB query builder, SQL querying in MongoDB, or a MongoDB query generator from third-party tools like Studio 3T are an effective way of being productive from day one.

Download the latest Studio 3T version here.

How MongoDB documents work

Below we’ll go through some theory, but if you want a more hands-on approach with query examples and quizzes, we recommend our free MongoDB 101 course for beginners, which covers the basics of MongoDB querying, aggregation, importing and exporting data, and much more, in just two hours.

A document is the basic unit of data in MongoDB. It contains fields or name-value pairs.

A group of documents then makes up a collection.

Each MongoDB document requires a unique _id field, which holds the ObjectId value.  This serves as the primary key for each document.  If this is missing, the MongoDB driver automatically creates it.

Fields

Within a MongoDB document, you can have fields of the following data types:

  • Double
  • String
  • Object
  • Array
  • Binary data
  • Undefined (deprecated)
  • ObjectId
  • Boolean
  • Date
  • Null
  • Regular expression
  • DBPointer (deprecated
  • JavaScript
  • Symbol (deprecated)
  • JavaScript (with scope)
  • 32-bit integer
  • Timestamp
  • 64-bit integer
  • Decimal128
  • Min key
  • Max key

The maximum size of a document is 16 MB, but MongoDB uses GridFS to accommodate larger documents.

What is GridFS?

GridFS is the file abstraction method MongoDB uses to store and retrieve files larger than 16 MB.

GridFS divides a file into equal chunks of 255 kB – except for the last chunk which can be as large as necessary – and stores each chunk as a separate document.

The file chunks are then saved in a MongoDB collection called chunks, and the file metadata in another called files. When you search GridFS for a file, it will reassemble the chunks as needed.

MongoDB documents also support arrays and embedded documents, and use the dot notation to access fields within them.

Arrays

Because data is stored flat in a MongoDB document, MongoDB can have fields with arrays – or a list of values – as values.

For example, the field marine-mammals below has an array of three string values (manatee, walrus, seal) as a value:

{
   _id: “North America”
   marine-mammals: [ “manatee”, “walrus”, “seal”]
}

Embedded documents

MongoDB allows you to embed documents within a document, to allow for the easier retrieval of information with just one query.

For example, take the two documents below. The first lists a specific marine mammal species and the continent it’s native to; the second lists the zoo(s) where one could visit this particular species.

{
   _id: “Florida manatee”
   continent: “North America”
}
{
   species_id: “Florida manatee”
   zoo_address: {
      name: “ZooTampa at Lowry Park”
      street: "1101 W. Sligh Avenue",
      city: "Tampa",
      state: "FL",
      zip: "33604"
      }
}

Instead of having to reference the second document every time you need the zoo location information, MongoDB allows you to embed the zoo_address field from the second document as a subdocument of the first:

{
   _id: “Florida manatee”
   continent: “North America”
   zoo_address: {
      name: “ZooTampa at Lowry Park”
      street: "1101 W. Sligh Avenue",
      city: "Tampa",
      state: "FL",
      zip: "33604"
      }
}

Dot notation

It’s nice that MongoDB lets you use arrays and embedded documents, but how do you query them?

MongoDB uses dot notation to fetch values from elements of an array and fields of an embedded document.

Using the document above as an example, we can query the marine mammal database to find out exactly which species we can find in the zoo ZooTampa at Lowry Park by writing the command:

db.marinemammals.find({"zoo_address.name" : "ZooTampa at Lowry Park"})

Most common MongoDB commands

Now that you’ve learned a bit about MongoDB, it’s time to hit the mongo shell and practice with the most common MongoDB commands for beginners.

Already using Studio 3T? Here’s how you can run the same common MongoDB commands in just a few clicks.

Log into MongoDB

use dbName
db.auth("userName", "password")

…making sure that the user exists in your current database.

Log out of MongoDB

db.logout()

List all databases

show dbs

Create a database (same as select a database)

use dbName

There isn’t really a dedicated command to create a database. MongoDB will take care of it the first time you store a document in a collection inside it.

Show current database

db

Drop a database

After making sure it’s the right one:

db.dropDatabase()

Note that this command does not require the name of the database you are going to drop; it drops the current database in which you are in.

So, the first thing you must do is change to the database that you want to drop, this way:

use databaseName
db.dropDatabase()

Create a user

Before we jump into commands relating to users and roles, note that MongoDB does not activate authentication by default. It is the database administrator who needs to do so when running the mongod service.

The first step in adding a MongoDB user is to define the database where the user will be created (let’s take admin):

use admin

Then, execute the following command:

db.createUser({
user : '<userName>',
pwd : '<password>',
 roles : [ { role : '<roleName>', db : '<dbName>' } | '<roleName>', …] 
})

Drop a user

Again, choose the database from which you want to drop the user:

use dbName

And run the command:

db.dropUser('<userName>')

Assign a role to a user

As you might have noticed, it’s already possible to grant roles when adding a new user.

But in case you need to do it later, run the command:

use '<dbName>'
> db.grantRolesToUser(
   '<userName>',
   [ { role : '<roleName>', db : '<dbName>' }, '<roleName>', … ]
)

Revoke a role from a user

Run the following command:

use '<dbName>'
db.revokeRolesFromUser(
   '<userName>',
   [ { role : '<roleName>', db : '<dbname>' } | '<roleName>' ]
)

Create a collection

db.createCollection("collectionName");

This command is not necessary. MongoDB will create it the first time we insert a document in it.

Drop a collection

db.collection_name.drop()

Insert a single document in a collection

db.collectionName.insert({ field1: “value1”, field2: “value2” })

Insert multiple documents in a collection

db.collectionName.insertMany([{field1: "value1"}, {field1: "value2"}])

List documents in a collection

db.collectionName.find()

Update a single document in a collection

db.collection.updateOne(<filter>, <update>, <options>)

Update multiple documents in a collection

db.collection.updateMany(<filter>, <update>, <options>)

Delete all documents in a collection

db.collection.deleteMany()

if you want to delete all the documents in a collection using the ‘remove’ command, do not forget to use an empty document:

db.collection.remove({})

Delete all documents that match a condition

db.collection.deleteMany({ field1: "value1" })

or

db.collection.remove({ field1: "value1" })

Looking for another MongoDB tutorial?

Thanks for making it all the way to the end of our Getting Started with MongoDB tutorial. We hope it helped you get to know how the most popular NoSQL database works, and perhaps determine if it might be a suitable database for your next project.

The learning of course doesn’t end here. If you want to hone your MongoDB skills, we recommend these resources:

  • Studio 3T – Not exactly a resource, but a MongoDB GUI and IDE with features that
    enable anyone to use MongoDB, regardless of your knowledge level.
  • Academy 3T – Sign up for MongoDB 101, the free MongoDB course for beginners that covers the basics in just two hours
  • MongoDB Tutorials – A roundup of the best MongoDB tutorials and courses, both free and paid
  • Learn MongoDB – A list of MongoDB courses, books, YouTube videos, and more

How helpful was this article?
This article was hideous
This article was bad
This article was ok
This article was good
This article was great
Thank you for your feedback!

About The Author

Kathryn Vargas

When she's not writing about working with MongoDB, Kathryn spends her free time exploring Berlin's food scene, playing the drums, learning languages (current mission: German), and hiking.

Article navigation

Related articles

  • Test your skills: Introduction to MongoDB and Studio 3T
  • Introduction to MongoDB Atlas
  • Date Tags: Getting It Right On DateTime
  • MongoDB Tutorial: Learn MongoDB in 2 Hours
  • How MongoDB Indexes Work (With Examples)

Studio 3T

MongoDB Enterprise Certified Technology PartnerSince 2014, 3T has been helping thousands of MongoDB developers and administrators with their everyday jobs by providing the finest MongoDB tools on the market. We guarantee the best compatibility with current and legacy releases of MongoDB, continue to deliver new features with every new software release, and provide high quality support.

Find us on FacebookFind us on TwitterFind us on YouTubeFind us on LinkedIn

Education

  • Free MongoDB Tutorials
  • Connect to MongoDB
  • Connect to MongoDB Atlas
  • Import Data to MongoDB
  • Export MongoDB Data
  • Build Aggregation Queries
  • Query MongoDB with SQL
  • Migrate from SQL to MongoDB

Resources

  • Feedback and Support
  • Sales Support
  • Knowledge Base
  • FAQ
  • Reports
  • White Papers
  • Testimonials
  • Discounts

Company

  • About Us
  • Blog
  • Careers
  • Legal
  • Press
  • Privacy Policy
  • EULA

© 2023 3T Software Labs Ltd. All rights reserved.

  • Privacy Policy
  • Cookie settings
  • Impressum

We value your privacy

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data.

By clicking “Accept all”, you consent to the storage of cookies and the processing of personal data for these purposes, including any transfers to third countries. By clicking on “Decline all”, you do not give your consent and we will only store cookies that are necessary for our website. You can customize the cookies we store on your device or change your selection at any time - thus also revoking your consent with effect for the future - under “Manage Cookies”, or “Cookie Settings” at the bottom of the page. You can find further information in our Privacy Policy.
Accept all
Decline all
Manage cookies
✕

Privacy Preference Center

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data. Please choose for which purposes you wish to give us your consent and store your preferences by clicking on “Accept selected”. You can find further information in our Privacy Policy.

Accept all cookies

Manage consent preferences

Essential cookies are strictly necessary to provide an online service such as our website or a service on our website which you have requested. The website or service will not work without them.

Performance cookies allow us to collect information such as number of visits and sources of traffic. This information is used in aggregate form to help us understand how our websites are being used, allowing us to improve both our website’s performance and your experience.

Google Analytics

Google Ads

Bing Ads

Facebook

LinkedIn

Quora

Hotjar

Reddit

Functional cookies collect information about your preferences and choices and make using the website a lot easier and more relevant. Without these cookies, some of the site functionality may not work as intended.

HubSpot

Social media cookies are cookies used to share user behaviour information with a third-party social media platform. They may consequently effect how social media sites present you with information in the future.

Accept selected