What is MongoDB and when to use it

MongoDB is a NoSQL database that stores data as JSON-like documents grouped into collections, with no fixed schema required. Use it for data that changes shape, such as profiles, catalogs, and events.

Updated 4 min read

Learning objectives

After reading this article you will be able to:

  • Understand MongoDB's document and collection model
  • Insert and query documents with the official Node.js driver
  • Know when MongoDB is a good fit and when another database is better
On this page

MongoDB shows up often in bots, APIs, and web apps. Instead of rigid tables, it stores each record as a document: a structure of fields and values that looks like a JSON object. That fits languages like JavaScript and Python, where data already moves around as objects.

If you are still weighing options, which database to choose compares MongoDB with the alternatives.

Tablefixed columnsidnameemailCollectiondifferent fields{ }{ }{ }{_id: ObjectId(…),unique _idname: "Alice",field: valueaddress: { city, state },nested objecthobbies: ["reading", …]array}
In a table every row has the same columns; in a collection each document carries its own fields, objects and arrays.

What is a document database?#

In a relational database you define tables with fixed columns, and every record follows the same shape. In a document database, each record is a document, and documents in the same collection can have different fields.

A MongoDB document looks like this:

javascript
{
  _id: ObjectId("507f1f77bcf86cd799439011"),
  name: "Alice",
  birthdate: ISODate("1990-01-01T00:00:00Z"),
  address: { city: "Springfield", state: "IL" },
  hobbies: ["reading", "hiking", "coding"]
}

Values can be strings, numbers, dates, other documents (like address), or arrays (like hobbies). Keeping the address inside the person's document avoids a join: one read returns everything.

How does MongoDB organize data?#

Four concepts cover most of it:

  • Document: one record, made of field and value pairs. Every document has a unique _id, which MongoDB creates if you do not provide one.
  • Collection: a group of documents, like a table but without a mandatory schema.
  • Database: a set of collections.
  • BSON: the binary format MongoDB uses to store documents. It extends JSON with types such as ObjectId, dates, and binary data.

If you want rules (required fields, types), you can add schema validation to a collection. Flexibility is a choice, not an obligation.

How does MongoDB work under the hood?#

Three features define the architecture, according to the official manual:

  • Replication with automatic failover: data is copied across several servers (a replica set). If the primary goes down, the others elect a new one.
  • Sharding: splitting data across machines by a key, to scale horizontally when one server is not enough.
  • ACID transactions: operations across several documents that either all apply or none do, including across sharded clusters.

In practice, a small project runs on a single server. Replication and sharding come in when data volume or availability requirements grow.

How do you use MongoDB with Node.js?#

Install the official driver and keep the connection string in an environment variable, never in your code:

bash
npm install mongodb
javascript
const { MongoClient } = require("mongodb");

const client = new MongoClient(process.env.MONGODB_URI);

async function main() {
  try {
    await client.connect();
    const users = client.db("app").collection("users");

    const { insertedId } = await users.insertOne({ name: "Ada", role: "engineer" });
    console.log("Inserted:", insertedId);

    const found = await users.find({ role: "engineer" }).toArray();
    console.log("Found:", found);
  } finally {
    await client.close();
  }
}

main().catch(console.error);

The users collection does not need to exist beforehand: MongoDB creates it on the first insert. For fast queries on fields you filter often, create an index with createIndex. Without one, the database scans the whole collection on every search.

What is MongoDB used for?#

MongoDB works well when data has a varying shape or is read as a block:

  • User profiles and settings: each user can have different fields.
  • Bots: per-server settings, preferences, and virtual economies, where each record is an object.
  • Product catalogs: items with different attributes per category.
  • Events and logs: many records of a similar but evolving shape.
  • Fast prototyping: the schema changes without migrations.

When should you not use MongoDB?#

Avoid it or think twice in these cases:

  • Highly related data: if you constantly join several entities, a relational database such as PostgreSQL is usually more natural.
  • Very large documents: the limit is 16 MiB per document, and nesting goes up to 100 levels. Large files belong in object storage, with the URL saved in the document.
  • Long transactions: the default limit is 60 seconds per transaction.
  • Ultra-fast caching: an in-memory store such as Redis is a better fit.

Flexibility has a cost too: without a schema, a typo in a field name goes unnoticed. Agree on naming conventions and turn on validation if you need it.

Which terms show up alongside MongoDB?#

  • NoSQL: a generic name for databases that do not use relational tables.
  • Atlas: the cloud service from MongoDB, Inc. You can also host MongoDB yourself or with other providers.
  • Mongoose: a Node.js library that adds schemas and models on top of the driver.
  • Aggregation pipeline: MongoDB's language for filtering, grouping, and transforming data in stages.
  • GridFS: a feature for storing files larger than 16 MiB by splitting them into chunks.

When you are ready to put a database online, how to host a database walks you through it.

How to do this on Square Cloud#

On Square Cloud, MongoDB hosting starts on the Standard plan; Hobby does not include databases. You create the database in the dashboard, always on a recent version, and it is ready in seconds. It runs in the same datacenter as your applications, with an average latency of about 1 ms, as a single node (standalone, no replica set) with mandatory TLS.

To connect your application, copy the full connection URL the dashboard gives you, save it as an environment variable (the MONGODB_URI from the example above) and restart the application. Download the certificate too: the client must trust the CA and present the .pem.

You take manual snapshots whenever you want, and every plan that includes databases also has a daily automatic snapshot. You can restore a snapshot into the same database, another one of the same engine or a new database, or download it as a .zip.

See details and plans at MongoDB hosting.

Database hosting

MongoDB, PostgreSQL, MySQL and Redis next to your app

Learn more

FAQs

Is MongoDB SQL or NoSQL?

It is NoSQL, specifically a document database. Instead of tables with rows and columns, it stores documents in collections, and you query it with MongoDB's own API and aggregation language, not SQL.

Does MongoDB support transactions?

Yes. It offers multi-document ACID transactions, including across sharded clusters. By default, a transaction can run for at most 60 seconds.

What is the maximum document size in MongoDB?

16 MiB per BSON document. For larger files, the docs point to GridFS, or you can keep the file in object storage and save only its URL in the document.

Is MongoDB better than PostgreSQL?

Neither wins everywhere. MongoDB suits data with a varying shape that you read one whole document at a time. PostgreSQL suits highly related data and queries with many joins.

Next articleHow much does PostgreSQL hosting cost?PostgreSQL hosting costs from zero to hundreds of dollars a month. See what sets the price (RAM, disk, replicas, traffic), billing models and how to estimate yours.

More in Databases

See all 24 articles