No SQL DB
NoSQL databases are document, key-value, graph, or wide-column stores.
Data structure used : Log Structured merge tree (LSM Tree)
Relational DB uses B Tree
B-Tree is optimized for read, thus updates are relatively expensive
Types of NoSQL Databases:
- Document-Oriented (e.g., MongoDB, CouchDB)
- Key-Value (e.g., Redis, DynamoDB)
- Column-Family (e.g., Cassandra, HBase)
- Graph Databases (e.g., Neo4j, Amazon Neptune)
MongoDB (Document-Oriented Database)
- MongoDB stores data as documents in a BSON format (similar to JSON).
- It’s highly scalable and flexible, ideal for applications where schema evolution is frequent.
Aggregation Framework
MongoDB’s aggregation framework allows you to perform advanced operations such as filtering, grouping, sorting, and projecting.
This is similar to SQL GROUP BY and JOIN operations.
a. Grouping Data
Use aggregation to group users by age and calculate the average age:
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.group("age").avg("age").as("averageAge"),
Aggregation.project("averageAge").and("age").previousOperation()
);
AggregationResults<AverageAge> results = mongoTemplate.aggregate(aggregation, User.class, AverageAge.class);
b. Filtering and Sorting
combine match and sort stages to filter and sort data
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("age").gt(20)),
Aggregation.sort(Sort.by(Sort.Order.asc("name"))),
Aggregation.limit(10)
);
List<User> users = mongoTemplate.aggregate(aggregation, User.class, User.class).getMappedResults();
Embedded Documents
use embedded documents for denormalized models.
public class User {
private String name;
private String email;
private Address address; // Embedded document
}
Redis (Key-Value Store)
Redis is an in-memory key-value store, known for its speed and simplicity. Ideal for caching, session management, and real-time data scenarios.