MongoDB Spring Example
SpringBoot app with MongoDB database using JPA
SpringBoot app with MongoDB database using JPA

1. Context

In this article, we have seen steps of creating a SpringBoot based imaginary TV program guide app that connects to PostgreSQL using JPA. The same code works for any relational database available in the market. We have to use the appropriate database driver and change the database configuration in the file. Using MongoDB in place of PostgreSQL is mostly the same. Here are the key differences:

  • The ORM class is referred here as a document class and the annotation @Document is used instead of @Entity.
  • The @Id field in the document and entity classes are handled differently
  • The Repository interface extends from MongoRepositoty instead of JpaReposity

2. JPA Repository and Document

Here is the ProgramDocument representing the program collection in MongoDB:

package org.openapex.tvguide.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;

@Document(collection = "program")
public class ProgramDocument {
    private String id;
    private String title;
    private String type;
    private String genre;
    private String certification;
    private List<String> actors;
    private String director;
    private String producer;


The Repository interface that extends from MongoRepository and provides Java APIs for all sorts of database operations.

package org.openapex.tvguide.dbaccess.repository;

import org.openapex.tvguide.model.ProgramDocument;
import org.springframework.stereotype.Repository;

public interface ProgramRepository extends MongoRepository<ProgramDocument, String> {

The Controller and service classes are the same whether PostgreSQL is used or a MongoDB used for persistence.

3. Database Configuration

Database configuration in file:

The database script to create a collection named program and add some sample programs:

use tvguide;

4. Conclusion

The Controller and service classes are the same whether PostgreSQL is used or MongoDB is used for persistence. In addition to channels endpoint, a new REST endpoint is exposed based on program data in MongoDB:

  • GET /guide/programs – lists all programs

The full code of this program guide app is available at GitHub: tvguide

MongoDB Spring Example
Be The First

Join our list to get instant access to new articles and weekly newsletter.

Tagged on:                         
0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x