mLab MongoDB on Heroku is shut down. Create a MongoDB Atlas cluster and put its connection string in the MONGODB_URI config var. Spring Boot reads that variable the same way it used to read the mLab add-on.
MongoDB Atlas
- Create a cluster in MongoDB Atlas. The free M0 tier is enough to start.
- Under Database Access, add a database user and a password.
- Under Network Access, allow
0.0.0.0/0. Heroku dynos do not have a fixed outbound IP. - Open Connect → Drivers and copy the
mongodb+srv://URI. Replace<password>with the database user’s password. If the password contains@,:, or/, URL-encode those characters. - Set the URI on the Heroku app:
heroku config:set MONGODB_URI="mongodb+srv://USER:PASSWORD@cluster.mongodb.net/stats?retryWrites=true&w=majority"heroku config should list MONGODB_URI. The Spring Boot app below reads it from the environment.
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);
}
...
}