Introduction:

MongoDB and Redis are both NoSQL databases.In other words they don’t use “traditional” relational database to manage data.

Although they have the same label – NoSQL – their storage concepts are very different:

MongoDB stores data on disk, whereas Redis is an in-memory database.

These aren’t the only differences between these two great tools, and that’s what we’re going to highlight in this article.

Main differences

 MongoDB Redis
SpeedThe schema-less structure ensures high speed when large volumes of data are stored on diskMuch faster than MongoDB, except when large amounts of data are stored in memory.
Storage ModelOn-disk storage by defaultIn-memory storage with on-disk persistence
Persistent storagePersistent storage Kubernetes’ persistent volume feature provides data and storage persistence.           Append-Only file data persistence and snapshots facilitate persistent storage.Data persistence for Append-Only files and snapshots facilitate persistent storage.
Memory usageDisk storage. Consumes a lot of memory, around 1 GB for 100,000 resources.Memory storage. Requires around 4 GB of RAM. Memory usage is higher than for MongoDB.
Data ModelBSON (Binary JSON) documents Document size is up to 16MB. Supports multiple data types: String, Boolean, Number (Integer, Float, Long, Decimal128…), Array, Object, Date, Raw Binary, GeoJSON.Key-value store Keys are binary safe strings with length up to 512MB. Values: String and multiple data structures, such as List, Set, Bitmap, Hash. The stored dataset is limited by the size of the available memory.
Query LanguageMongoDB Query API Search documents by single or multiple keys, by range or by text search. Perform graph traversals and geospatial queries. Create materialized views on demand. Analyse data using advanced aggregation pipelines.Key-value queries only Limited query functionality. By design—only primary key access. Query functionality can be extended with third-party Redis Modules.
IndexesRich and easy to create indexes Secondary indexes enable developers to build applications that can query and analyze the data in multiple ways. You can create compound, TTL, text, geospatial, hashed, and wildcard indexes. MongoDB Atlas’s Performance Advisor suggests new indexes to improve query performance. MongoDB Atlas also allows you to build indexes in a rolling fashion to minimize the impact on the working system.Hard to build secondary indexes Secondary indexes should be manually built and maintained.
Scaling-OutBuilt-in Sharding Sharding allows you to scale out across multiple nodes and geographic regions. Multi-cloud support, consistent backups with point in time recovery by MongoDB Atlas. Partition data by range, hash, or zone. Perform cross-shard operations. Language-agnostic feature supported by all official and community supported drivers.Redis Cluster No multi-shard database operations. No consistent cross-shard backups and no strong consistency. Hash sharding only. Manual maintenance of the shards. Limited driver support with community maintained libraries.
High AvailabilityReplica sets Create up to 50 copies of your data, provisioned across separate nodes, data centers, and geographic regions. Automatic failover with replica set elections.Redis Sentinel Monitor the state of your Redis Cluster with a set of independent processes. Manual failover required if you need to promote a replica in another data center to master.
Transactional Data IntegrityMulti-document ACID transactions Multi-statement with easy-to-use syntax similar to relational databases.MULTI command Muti-record transaction support with the MULTI command. No rollbacks support—you need to implement rollback in the application code.
Data aggregationMongoDB Atlas uses the aggregation pipeline builder to build and process aggregation pipelines MongoDB Atlas uses the aggregation pipeline builder to build and process aggregation pipelinesMap reduction functions and aggregation pipelines are used

When to use MongoDB and when to use Redis ?

Regarding your need and your infrastructure you will have to select one of the tool ( sometime both )

Also the best database system for you depends very much on the type of application you are developing

Take also care about hardware considerations.

If high speed and low latency are the deciding factors, Redis is the best candidate for optimum performance. It can handle the workload of applications such as fraud detection and modern game development, which need to process large amounts of constantly changing real-time data quickly and efficiently.

MongoDB, on the other hand, performs better in terms of scalability and reliability, making it ideal for applications that store large volumes of data over a long period of time. Examples include e-commerce websites, photo-sharing applications, etc.

What is MongoDB?

MongoDB is the primary document database of choice by architects and developers for many uses. The main features of MongoDB that have been built into it since day one are: A distributed architecture that allows systems to scale to multiple nodes.

  • What is a document?

A document data model that naturally maps to objects in your code. Focus on a great developer experience with official support for ten programming languages. MongoDB stores data on disk in BSON (binary JSON) records called documents.

Documents have a flexible schema, which means that the structure of the stored data can change over time. When editing a document, you can add new fields or delete existing fields.

  • What is a collection?

Similar or related documents are grouped into collections.

Documents in the same collection can have different fields. However, a flexible model does not mean chaotic data – you can define validation rules for your collections according to your application requirements.

  • What is Mongo Atlas?

MongoDB Atlas is MongoDB’s multi-cloud database platform. It allows you to share and transfer your data between all major cloud providers – Amazon Web Services (AWS), Microsoft Azure and Google Cloud Platform (GCP),you have to pay for this feature.

What is Redis?

Redis, short for Remote Dictionary Server, is an in-memory key-value store. Most of its advantages and disadvantages stem from this definition.

  • What is In-memory storage?

In-Memory means that the data is stored in the host’s RAM (Random Access Memory) and not on disk. Reading and writing RAM is much faster than performing disk operations. This allows in-memory stores like Redis to perform millions of queries per second. There are disadvantages to the in-memory model. RAM is much more expensive than disk storage, making it not cost-effective for large data sets. Simply put, your dataset is limited by the memory allocated to the Redis process.

  • What is a key value store?

A key value stores process data as a single collection.

Each record amount is a pair – a key and an associated value.

Keys must be unique because they are used to retrieve values.

Data types and allowed key-value structures are application-specific. In keys, Redis allows binary security strings of up to 512 megabytes. You can choose from a larger number of data structures for values. Supported types are strings, lists, sets, maps, and streams.

The downside of using a key-value store like Redis is that it lacks a query language.

Additionally, Redis does not natively support secondary indexes. This limits the flexibility of your data. If you need an access path to data that is not a primary key, you must create and manage your own indexes, storing them in already limited memory.

  • When you can use Redis?

Depending on the configuration, Redis can be used for different purposes, the most common being a cache, a session management system, or a message broker. Due to the shortcomings of the in-memory storage model, the use of Redis as a storage system is rare.

Redis is often used in conjunction with a disk-based database such as MongoDB.

Although a disk-based database is the primary storage solution, Redis can be used as a caching layer or for real-time analytics.

If you already use MongoDB, you can achieve similar results without adding Redis to your system. MongoDB’s WiredTiger storage engine has an internal cache that may be sufficient for your application’s working set. In addition, MongoDB Enterprise Advanced provides an in-memory storage engine.

Data Storage on MongoDB vs. Redis:

The most obvious difference between MongoDB and Redis is their conceptually different data storage model.

Indeed , Redis is an in-memory data store, while MongoDB’s default storage engine, WiredTiger, stores data on disk.

Redis data persistence

Despite being an in-memory store, Redis stores data on disk to ensure data persistence. If a Redis process crashes and restarts, it can recover data from disk. Redis provides various persistence options that can be customized according to your application requirements. More writing to disk means better data throughput, but also lower performance.

MongoDB in-memory storage

MongoDB supports an in-memory storage engine as part of MongoDB Enterprise. The in-memory storage engine combines the predictable latency benefits of in-memory storage models with the versatile query capabilities of MongoDB.

The in-memory storage engine does not write data to non-volatile memory. For data resiliency, you can deploy copy sets that use the default in-memory storage engine and persistent storage engine. In the event of a crash and restart, nodes using the in-memory storage engine can synchronize nodes using persistent storage.

For that point, Redis offers this feature natively.

Scalability of Redis vs MongoDB

MongoDB has a horizontal scale-out architecture built-in from day one. Horizontal scaling is achieved with sharding which allows you to distribute data across multiple nodes. Data is partitioned across nodes based on the configured shard key.

Redis Cluster is Redis’s solution for scaling out by sharding data across multiple nodes.

Can we use Redis with MongoDB?

Of course we can! 🙂

Redis can be used as a cache, a message broker, or a session manager together with a persistent storage database such as MongoDB.

Customers often use it as a cache for MongoDB.

Also it depends if you want to add some new features, which have a cost.

Conclusion

Depending of your need you will have to choose between MongoDB or Redis:

Redis is more efficient and give high response time when you have to work on streams and real time data whereas MongoDB will be great for applications that store large volumes of data over a long period of time, you can add some advanced feature by upgrading to the enterprise version.

But instead of choosing one, why not try combining the two?!

Feel free to share with us and visit my other blogs and also the dbi bloggers for new tips and posts,stay tuned for the next blog!