First of all you need to install a MongoDB add-on for your Heroku application - click on “Find more add-ons” under the “Resources” tab, find “mLab MongoDB” (they have a free plan to start with), click on it and follow installation instructions.

Once you’re done you’ll see the “mLab MongoDB” in the list of your add-ons. Also the MONGODB_URI variable will be added to your “Config Vars”.

Then follow the example below

application.properties

# MONGODB
spring.data.mongodb.uri=${MONGODB_URI}

Spring Boot MongoDB starter dependency

...
  <dependencies>
    ...
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    ...
  </dependencies>
...

MongoDB collection class

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "stats")
public class StatEntry {

    @Id
    public String id;

    private long time;

    private String referrer;

    private String site;

    ...

}

MongoDB repository class

import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface StatEntryRepo extends MongoRepository<StatEntry, String> {

    StatEntry findOneById(String id);

    List<StatEntry> findAll();

    void delete(StatEntry entry);

    void deleteAll();

}

MongoDB repo usage example

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.UUID;

@Component
public class StatService {

    @Autowired
    public StatEntryRepo statsRepo;

    public void addStatEntry(String site, String referrer) {
        StatEntry entry = new StatEntry();
        entry.setSite(site);
        entry.setReferrer(referrer);
        entry.setTime(Instant.now().toEpochMilli());
        entry.setId(UUID.randomUUID().toString());
        statsRepo.save(entry);
    }

    ...

}