1. Knowledge Base
  2. MongoDB Tutorials
  3. Getting Started with MongoDB – An Introduction

Getting Started with MongoDB – An Introduction

Thinking of adding MongoDB to your database mix? 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.

Looking to get started with our MongoDB GUI Studio 3T instead? Find the guide here.

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

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
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
Horizontal scaling, on the other hand, 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.

MongoDB 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

High availability in MongoDB is provided by 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.

How MongoDB documents work

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 serves as a primary key. 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 – assuming you’ve already downloaded and installed it – it’s time to hit the mongo shell and practice with the most common MongoDB commands for beginners.

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" })

MongoDB resources

Thanks for making it all the way to the end of our Introduction to MongoDB! We hope this article 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. 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.
  • MongoDB Tutorials – Learn MongoDB through tutorials for newcomers and pros alike, with topics ranging from MongoDB aggregation to user management.
  • The Complete Developers Guide to MongoDB – Stephen Grider’s comprehensive beginner’s course walks you through MongoDB fundamentals, with a focus on Node.js and test-driven exercises.
Updated on November 13, 2018

Was this article helpful?

Related Articles