Logo of the site

My cheatsheet

MongoDB cheatsheet

This is a quick reference cheat sheet for understanding and writing MongoDB.

# Getting started

What is a Database?

Databases are systems that store, modify, and access structured collections of information electronically.

A Database Management System (DBMS) allows developers to interact with databases using code or a graphical interface.

Databases can store various types of data: text, numbers, dates, files, and more.

DBMS Analogy

If a database is a bucket that stores data, the DBMS is the software that wraps around the bucket and provides access via a language or GUI.

Relational Databases

Relational databases organize data into structured tables with rows and columns, and use predefined schemas and relationships.

They all use SQL to query and manipulate data.

While powerful, they may be expensive to set up and scale. Performance and cost are key considerations.

Non-relational Databases

Non-relational or NoSQL databases do not follow the traditional table-based model.

They allow more flexible schemas and are often easier to scale horizontally. However, they lack a standard query language and can be harder to maintain due to unstructured data.

NoSQL stands for “not-only SQL”. Types include:

  • Key-Value Stores
  • Document Stores
  • Graph Databases
  • Column-Oriented Databases

MongoDB Overview

MongoDB is a document-based NoSQL database. Each instance can contain multiple databases, each with collections (similar to tables) containing documents (records).

Documents are stored as field-value pairs using JSON format for input, and internally stored as BSON.

JSON: human-readable, less efficient. BSON: binary, highly efficient.

The combination of document model and JSON/BSON support makes MongoDB a flexible and performant database.

Modeling one-to-one embedded relationships (MongoDB Docs)

Advantages of NoSQL

  • Flexibility & Scalability: Schema-less design allows easy adaptation to changing data.
  • Custom Query Language: Each NoSQL DB can use its own language, optimized for its model.

Disadvantages of NoSQL

Due to their unstructured nature, data in NoSQL databases can become hard to track and maintain.

Each database has its own query language — learning curve increases with each new NoSQL system.

# Commands

Show All Databases

See all databases inside a cluster

show dbs

This command outputs a list of all databases in the current instance along with the disk space each uses

online_plant_shop       73.7 KiB
plant_lovers_meet       55.7 MiB
my_portfolio_site       9.57 MiB
admin                   340 KiB
local                   1.37 GiB
config                  12.00 KiB

The admin, config, and local databases are system databases used by MongoDB to configure the instance.

Select a Database

Navigate to a specific database

use online_plant_shop

This places you inside the online_plant_shop database, where you can view and manage all of its collections.

If the specified database does not exist, MongoDB will create it and switch you into that database.

The terminal prompt will change to indicate the current database (e.g., from test> to online_plant_shop>).

Other commands

  • dbOutputs the name of the database you are currently using
  • show collectionsList all collections inside the current database

# Operators and methods

Comparison Operators

Operators can be used for numbers, dates, or even strings

  • $gt greater than
  • $gte greater or equal than
  • $lt lower than (also for string)
  • $lte lower or equal than (also for string)
  • $eq equal to

Query on Arrays

If an array of values is specified, the array is matched with the given array with the exact values and order

array : ["val1", "val2"]

If a single value is specified as a string, all arrays containing that element will be returned

array : "val1"
  • $all Returns all arrays that contain the given elements without considering the order
  • $elemMatch Used to specify multiple criteria on the elements of an array field, so that at least one element satisfies all criteria

Methods

  • .sort() Sorts query results by a specified field (ascending 1 or descending -1). You can include a projection to include or exclude fields
  • .count() Returns the number of documents that match a query
  • .limit() Can be chained to .find() to specify the maximum number of documents returned
  • $exists Matches documents that contain the given field
  • $ne Checks if a field is not equal to a specified value
  • $and, $or Perform logical AND and OR operations
  • .pretty() Formats query output in a more readable way

Embedded Documents Query

When a record has an embedded document, query its fields using dot notation (.) and wrap field names in quotation marks.

# CRUD operations

General Syntax

Queries in MongoDB are performed on a specific collection. General syntax:

db.collectionName.operator()

.find()

The .find() method is used to search for documents in a collection.

db.collectionName.find({attribute: value}, {pippo:1, pluto:0})

This query returns documents that match the filter, showing only the pippo field (and excluding pluto).

  • The filter defines the criteria for matching documents
  • The projection specifies which fields to include (1) or exclude (0) in the output

Cursor and Iteration

The .find() method returns a cursor. A cursor is an object that points to the matching documents and returns them in batches.

If no arguments are provided, it matches all documents in the specified collection.

To see the next batch of documents, use the it command (short for iterate) in the Mongo shell.

Query on embedded fields

When querying an embedded document, use dot notation. For example, to find documents where an embedded field value is less than or equal to a specified value

db.collectionName.find({"parent_field.embedded_field": { $lte: value }})