Spring / Spring Boot 4 Basics Interview Questions
How do you use Spring Data MongoDB and other NoSQL stores in Spring Boot 4?
Spring Boot 4 auto-configures connections to MongoDB, Redis, Cassandra, Elasticsearch, and other NoSQL stores when their starters are on the classpath. The programming model mirrors Spring Data JPA but without SQL.
// MongoDB entity: import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "products") // MongoDB collection name public record Product( @Id String id, // MongoDB ObjectId String name, BigDecimal price, String category, Instant createdAt ) {} // MongoDB repository: public interface ProductRepository extends MongoRepository<Product, String> { List<Product> findByCategory(String category); List<Product> findByPriceLessThan(BigDecimal maxPrice); // MongoDB query annotation: @Query("{ \"category\": ?0, \"price\": { \"$lt\": ?1 } }") List<Product> findByCategoryAndMaxPrice(String category, BigDecimal maxPrice); } # application.yml: MongoDB connection: spring: data: mongodb: uri: mongodb://localhost:27017/products-db # or: host: localhost port: 27017 database: products-db username: ${MONGO_USER} password: ${MONGO_PASS} # application.yml: Redis connection: spring: data: redis: host: localhost port: 6379 password: ${REDIS_PASS} timeout: 2s // Redis template usage: @Service public class SessionService { private final RedisTemplate<String, Object> redisTemplate; public void store(String key, Object value, Duration ttl) { redisTemplate.opsForValue().set(key, value, ttl); } }
More Related questions...