I am using spring boot web application which connects to mongo db which is working out of the box. I just use the following properties:
spring.data.mongodb.h
MongoClientOptions is a class which has the required properties.
Programmatically If you have configured your MongoDB programmatically, then below is the code snippet to help you out.
DB mongoDb;
MongoClient mongoClient = new MongoClient(new ServerAddress(url, port),
MongoClientOptions.builder()
.socketTimeout(3000)
.minHeartbeatFrequency(25)
.heartbeatSocketTimeout(3000)
.build());
mongoDb = mongoClient.getDB(dbname);
XML Configuration - Advanced
Also refer here for complete documentation.