阿里云主机折上折
  • 微信号
Current Site:Index > The difference between NoSQL databases and relational databases

The difference between NoSQL databases and relational databases

Author:Chuan Chen 阅读数:20368人阅读 分类: MongoDB

Differences in Data Models

The most fundamental distinction between NoSQL databases and relational databases lies in their data models. Relational databases employ a rigid tabular structure, storing data in rows and columns that adhere to a predefined schema. For instance, a user table might contain fixed fields like id, name, and email. In contrast, NoSQL databases like MongoDB use a flexible document model, storing data in a BSON format similar to JSON without requiring a predefined structure.

// MongoDB document example
{
  _id: ObjectId("5f8d8b7b9d5b3c2e1c9e8b7a"),
  name: "Zhang San",
  age: 30,
  address: {
    city: "Beijing",
    street: "Jianguo Road, Chaoyang District"
  },
  hobbies: ["Reading", "Swimming", "Photography"]
}

Relational databases require all records to follow the same structure. If a user lacks a phone number field, that field must still be retained as NULL. MongoDB, however, allows each document to have a completely different structure. This flexibility is particularly suitable for semi-structured data or rapidly evolving development scenarios.

Query Language Comparison

Relational databases use standardized SQL for queries, featuring powerful JOIN operations and robust transaction support. For example, an SQL query to retrieve user and order information:

SELECT users.name, orders.product 
FROM users 
JOIN orders ON users.id = orders.user_id
WHERE users.age > 25;

MongoDB uses a JSON-based query syntax. While it doesn't support table joins, it offers rich query operators. The same query in MongoDB might require two separate queries:

// MongoDB query example
const users = await db.collection('users').find({ age: { $gt: 25 } }).toArray();
const userIds = users.map(user => user._id);
const orders = await db.collection('orders').find({ user_id: { $in: userIds } }).toArray();

MongoDB 4.0 introduced the $lookup operator to implement LEFT OUTER JOIN-like functionality, but its performance is generally inferior to native JOINs in relational databases.

Different Scaling Approaches

Relational databases typically use vertical scaling (scale-up), improving performance by adding hardware resources like CPU and memory. NoSQL databases like MongoDB are designed for horizontal scaling (scale-out), supporting sharding to distribute data across multiple servers.

A MongoDB sharded cluster consists of three components:

  1. Shard: A mongod instance storing actual data
  2. Config Server: Stores cluster metadata
  3. Query Router (mongos): Routes client requests to the correct shard

This architecture enables MongoDB to handle petabytes of data, whereas traditional relational databases often encounter performance bottlenecks with extremely large datasets.

Transaction Support

Relational databases are built around ACID transactions (Atomicity, Consistency, Isolation, Durability). For example, a bank transfer operation:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE user_id = 2;
COMMIT;

MongoDB only supported single-document transactions before version 4.0. Version 4.0 introduced multi-document transactions:

const session = db.getMongo().startSession();
session.startTransaction();
try {
  const accounts = session.getDatabase('bank').accounts;
  accounts.updateOne({ user_id: 1 }, { $inc: { balance: -100 } });
  accounts.updateOne({ user_id: 2 }, { $inc: { balance: 100 } });
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}

Although MongoDB now supports transactions, the performance overhead in distributed environments is significant. It's generally recommended to avoid frequent use of multi-document transactions through proper data modeling.

Indexing Mechanisms

Both database types use indexes to speed up queries, but their implementations differ. Relational databases typically use B+ tree indexes, while MongoDB supports multiple index types:

  1. Single-field index: db.users.createIndex({ name: 1 })
  2. Compound index: db.users.createIndex({ name: 1, age: -1 })
  3. Multikey index: For array fields db.users.createIndex({ hobbies: 1 })
  4. Geospatial index: db.places.createIndex({ location: "2dsphere" })
  5. Text index: Supports full-text search db.articles.createIndex({ content: "text" })

MongoDB indexes are stored in BSON format and deeply integrated with the document data model. A notable difference is that MongoDB allows indexing on nested documents and arrays, a feature most relational databases lack.

Data Consistency

Relational databases emphasize strong consistency, ensuring all clients see the latest data at any given time. MongoDB defaults to eventual consistency, particularly in sharded clusters, which can lead to read skew issues.

MongoDB offers tunable consistency levels:

  • Write Concern: Controls write operation acknowledgment levels
    db.products.insertOne(
      { item: "Notebook", qty: 100 },
      { writeConcern: { w: "majority", wtimeout: 5000 } }
    )
    
  • Read Preference: Specifies which node to read from
    db.collection.find().readPref("secondaryPreferred")
    

This flexibility allows developers to balance consistency and performance according to different business needs.

Suitable Use Cases

Relational databases are ideal for:

  • Financial systems requiring complex transactions
  • Applications with fixed data structures and complex relationships
  • Scenarios demanding strict data integrity

MongoDB and other NoSQL databases excel at:

  • Handling large volumes of unstructured or semi-structured data
  • Rapidly evolving internet applications
  • High-throughput read/write operations
  • Geospatial data and real-time analytics

For example, a content management system storing articles and comments is well-suited for MongoDB, while a bank's core system is better served by a relational database. In practice, both database types are often used together, forming a polyglot persistence architecture.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.