How to set MongoDB connection string as an environment variable for Spring Data MongoDB
The Spring configuration gives a lot of flexibility on how to configure different parts of the framework and its dependencies. When it comes to Spring Data MongoDB, the same is true. However, some of the configuration options are better choice depending on the situation (environments) or if the property is secret or not. For example, having a database Mongo database connection string (URI) in the application.properties
files as spring.data.mongodb.uri
is fine during the development or in the staging environment. On the other hand, a production database connection string hardcoded and committed to the source control won’t be considered OK in many situations. A very convenient way and at the same time supported by most of the cloud providers is setting secrets and configuration options as environment variables.
The environment variable with the database connection string (URI) expected by the Spring Data MongoDB is SPRING_DATA_MONGODB_URI
. No changes are needed in the application code as the MongoDB Spring Data will look for the variable by default and use it if present.
export SPRING_DATA_MONGODB_URI=mongodb://localhost:27017/my-database