NoSQL Integration in .NET Core (MongoDB & Redis)
|
|
ποΈ NoSQL Integration in .NET Core
π Overview
NoSQL databases provide flexible, schema-less, and high-performance
data storage options. In .NET Core, two popular NoSQL databases are:
- MongoDB β A document-oriented database (JSON-like documents).
- Redis β An in-memory key-value store, often used for caching, sessions, and pub/sub.
π MongoDB Integration Example
// Install-Package MongoDB.Driver
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Threading.Tasks;
public class Product
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class MongoExample
{
public static async Task Main()
{
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("ShopDb");
var collection = database.GetCollection<Product>("Products");
// Insert
await collection.InsertOneAsync(new Product { Name = "Laptop", Price = 1200 });
// Read
var products = await collection.Find(new BsonDocument()).ToListAsync();
products.ForEach(p => Console.WriteLine($"{p.Name} - {p.Price}"));
}
}
π Redis Integration Example
// Install-Package StackExchange.Redis
using StackExchange.Redis;
using System;
using System.Threading.Tasks;
public class RedisExample
{
public static async Task Main()
{
var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
var db = redis.GetDatabase();
// Set
await db.StringSetAsync("product:1", "Laptop");
// Get
var value = await db.StringGetAsync("product:1");
Console.WriteLine($"Product: {value}");
}
}
β
Advantages
MongoDB
- Flexible schema (JSON-like documents).
- Great for hierarchical or semi-structured data.
- Scales horizontally with sharding.
Redis
- Extremely fast (in-memory operations).
- Great for caching, session storage, leaderboards, pub/sub.
- Supports data structures (lists, sets, hashes).
β οΈ Disadvantages
MongoDB
- Less suited for complex relational queries.
- Requires careful schema design for performance.
- Eventual consistency in distributed setups.
Redis
- Data is volatile unless persistence is enabled.
- Not ideal for large datasets that donβt fit in memory.
- Limited querying compared to databases.
π§ Best Practices
- Use MongoDB for document storage and Redis for caching/performance.
- Design MongoDB collections with access patterns in mind.
- Enable Redis persistence (AOF/RDB) if data durability is required.
- Use connection pooling for both MongoDB and Redis.
- Secure connections with authentication and TLS.
π Precautions
- Monitor MongoDB indexes to avoid performance bottlenecks.
- Set Redis eviction policies to handle memory limits.
- Handle transient failures with retry policies (Polly).
- Use separate databases/collections for different domains.
π― Summary
- MongoDB is best for flexible, document-based storage.
- Redis is best for caching, real-time performance, and ephemeral data.
- In many systems, they are used together: MongoDB as the primary store, Redis as a high-speed cache.