MongoDB Introduction

Learn what MongoDB is and how it stores data as flexible JSON-like documents, how databases, collections and documents fit together, how it differs from SQL databases, and how to connect with mongosh or MongoDB Atlas.

Lesson 1 of 43Beginner17 min read

MongoDB is the most popular document database. Instead of storing data in tables with fixed columns, as SQL databases do, it stores documents: records that look like JSON objects, with fields, nested objects and arrays. A product, a user profile or an order with all its items can be stored as one document, shaped the way your application already thinks about it.

This flexibility makes MongoDB quick to start with and a natural partner for JavaScript and Node.js. Documents in the same collection can have different fields, so adding a new property doesn't require changing a schema first. MongoDB also scales well: it can copy data across servers for safety and split huge collections across many machines.

MongoDB is used for product catalogues, content management, user profiles, real-time analytics, mobile app back ends and Internet of Things data. In this lesson you'll learn the core concepts of databases, collections and documents, see how they compare with SQL, connect with the mongosh shell or MongoDB Atlas, and insert and read your first documents.

Documents, collections and databases

MongoDB Shell
{
  _id: 1,
  name: 'Desk lamp',
  price: 24.5,
  tags: ['home', 'lighting'],
  stock: { warehouse: 12, store: 3 }
}
  • A document is a set of field and value pairs. Values can be strings, numbers, booleans, dates, arrays and nested documents.
  • Every document has a unique _id. If you don't provide one, MongoDB creates an ObjectId automatically.
  • A collection groups related documents, such as products or orders. It's similar to a table.
  • A database holds collections. One MongoDB server can host many databases.
  • Documents are stored as BSON, a binary form of JSON that adds types such as dates, ObjectIds and exact decimals.

MongoDB compared with SQL

SQLMongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField
Primary key_id
JOINEmbedded documents, or $lookup
Fixed schemaFlexible schema, with optional validation

Neither is better in general. Relational databases shine with highly connected data and complex reporting, as covered in the SQL tutorial. MongoDB shines when data naturally forms self-contained documents, when the structure changes often, or when you need to scale horizontally.

Getting started with mongosh

You can run MongoDB on your own machine with MongoDB Community Server, in Docker with docker run -d -p 27017:27017 mongo, or in the cloud with MongoDB Atlas, which offers a small starter cluster for learning. Connect with mongosh, MongoDB's interactive shell:

Terminal
mongosh "mongodb://localhost:27017"
MongoDB Shell
show dbs                 // list databases
use shop                 // switch to (or create) the shop database
show collections         // list collections in the current database
db.products.insertOne({ name: 'Mug', price: 8.5 })
db.products.find()

A database and collection are created automatically the first time you insert into them. MongoDB Compass is a graphical tool for browsing the same data.

MongoDB Basics Syntax

mongosh basics

show dbs
use shop
show collections
db.products.insertOne({ name: 'Pen', price: 1.2 })
db.products.find()
db.products.findOne({ name: 'Pen' })
db.products.countDocuments()
db.products.drop()

MongoDB Basics Summary

  • MongoDB is a document database that stores JSON-like BSON documents.
  • Documents live in collections, and collections live in databases.
  • Every document has a unique _id; MongoDB creates an ObjectId if you don't supply one.
  • Collections don't require every document to have the same fields.
  • Connect with mongosh or Compass to a local server, Docker or MongoDB Atlas.

MongoDB Basics Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Your first documents

MongoDB Shell
use shop
db.products.insertOne({ _id: 1, name: 'Mug', price: 8.5 })
db.products.insertOne({ _id: 2, name: 'Lamp', price: 24, colour: 'black' })
db.products.find()
db.products.countDocuments()
Output
switched to db shop
{ acknowledged: true, insertedId: 1 }
{ acknowledged: true, insertedId: 2 }
[
  { _id: 1, name: 'Mug', price: 8.5 },
  { _id: 2, name: 'Lamp', price: 24, colour: 'black' }
]
2
Line-by-line explanation
  1. Line 1use switches to the shop database, creating it when data is first stored.
  2. Line 2insertOne adds a document; the collection is created automatically.
  3. Line 3This document has a colour field the first one doesn't, which is allowed.
  4. Line 4find with no filter returns every document in the collection.
  5. Line 5countDocuments returns how many documents match, here all of them.
Example 2

Automatic ObjectIds and nested data

MongoDB Shell
db.users.insertOne({
  name: 'Ada',
  email: 'ada@example.com',
  address: { city: 'Leeds', postcode: 'LS1 4AP' },
  interests: ['maths', 'engines']
})
db.users.findOne({ name: 'Ada' }, { _id: 0 })
Output
{
  acknowledged: true,
  insertedId: ObjectId('...')
}
{
  name: 'Ada',
  email: 'ada@example.com',
  address: { city: 'Leeds', postcode: 'LS1 4AP' },
  interests: [ 'maths', 'engines' ]
}
Line-by-line explanation
  1. Lines 1 to 6No _id is given, so MongoDB generates a unique ObjectId; its value differs every time.
  2. Line 4A nested document groups related fields.
  3. Line 5Arrays store lists directly inside the document.
  4. Line 7The second argument to findOne chooses fields to return; _id: 0 hides the id.
Example 3

Listing databases and collections

MongoDB Shell
use library
db.books.insertOne({ title: 'Dune', year: 1965 })
db.authors.insertOne({ name: 'Frank Herbert' })
show collections
db.books.drop()
show collections
Output
switched to db library
{
  acknowledged: true,
  insertedId: ObjectId('...')
}
{
  acknowledged: true,
  insertedId: ObjectId('...')
}
authors
books
true
authors
Line-by-line explanation
  1. Line 1A new database exists as soon as something is stored in it.
  2. Lines 2 to 3Each insert creates its collection if it doesn't exist yet.
  3. Line 4show collections lists the collections in the current database.
  4. Line 5drop deletes a whole collection and its documents, so use it carefully.

Common MongoDB Basics Mistakes

Expecting a fixed schema

Don't
db.products.insertOne({ name: 'Mug', prcie: 8.5 })   // the typo creates a new field without complaint
Do
db.createCollection('products', {
  validator: { $jsonSchema: { required: ['name', 'price'] } }
})

Forgetting which database you're in

Don't
db.products.find()                     // empty: you're still in the "test" database
Do
use shop
db.products.find()

Treating MongoDB exactly like SQL

Don't
// orders, order_items, item_options and addresses in separate collections, joined on every page view
Do
// one order document containing its items and the delivery address used at the time

MongoDB Basics in Real Projects

Where MongoDB is used

Online shops store product catalogues in MongoDB because products in different categories have very different attributes. Content platforms store articles with flexible blocks, games store player profiles and inventories, and IoT systems store large volumes of sensor readings with time series collections. Many Node.js teams pick MongoDB with the official driver or Mongoose, as covered in the Node.js driver lesson.

MongoDB Basics FAQ

Is MongoDB free to use?

MongoDB Community Server is free to download and run on your own machines, and the official mongo Docker image is the same edition. MongoDB Atlas, the hosted cloud service, has a free tier that's big enough for learning and small projects. Paid options add features such as managed backups, larger clusters and enterprise security tools.

What is the difference between mongo and mongosh?

mongosh is the current MongoDB Shell, with syntax highlighting, autocompletion and a modern Node.js-based JavaScript engine. The older mongo shell was deprecated and is no longer shipped with MongoDB 6.0 and later. Commands such as show dbs, use shop and db.products.find() work the same way in both.

How big can a MongoDB document be?

A single document can be at most 16 MB of BSON, which is plenty for an order, a profile or an article. If a document keeps growing without limit, for example by appending every comment or log entry to one array, split that data into its own collection instead. Large files such as videos belong in object storage or GridFS, not inside a normal document.

Does MongoDB support joins like SQL?

Yes, the $lookup stage of the aggregation pipeline joins documents from another collection. In practice you need joins less often, because related data that's read together is usually embedded in one document. When data is shared by many documents, such as a customer referenced by many orders, you store a reference and use $lookup when you need both.

How do I check which version of MongoDB I'm running?

In mongosh, run db.version() to see the server version, for example 7.0.12. From a terminal, mongod --version prints the version of the installed server binary and mongosh --version prints the shell's version. The server version matters most, because it decides which operators and features are available.

MongoDB Basics Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the command that switches to the shop database.

 shop
Multiple choiceeasy

What is a collection in MongoDB most similar to in SQL?

Multiple choicemedium

What happens if you insert a document without an _id?

Predict the outputmedium

A collection has 3 documents. What does this return?

db.items.insertOne({ name: 'Pen' })
db.items.countDocuments()
Multiple choicehard

Can two documents in the same collection have different fields?

MongoDB Basics Quiz

5 questions to check what you learned.

  1. What format does MongoDB use to store documents?

    • CSV
    • XML
    • BSON, a binary form of JSON
    • YAML
  2. What is mongosh?

    • A Node.js framework
    • MongoDB's interactive command-line shell
    • A backup tool
    • A query language
  3. When is a collection created?

    • Automatically, the first time a document is inserted into it
    • Only with createCollection
    • When the server starts
    • When you run show collections
  4. What is MongoDB Atlas?

    • A query editor
    • A JSON library
    • A Node.js driver
    • MongoDB's managed cloud database service
  5. Which kind of data suits MongoDB especially well?

    • Data that must be joined across many tables for every query
    • Self-contained records whose structure varies or changes often, like product catalogues
    • Only numbers
    • Only small datasets