title: Too many connections error while using mongodb with java
body: <p>I use MongoDbFactory to connect to mongodb with Java. But the mongo service throws socket exception at least once every hour. Hence I am forced to restart mongodb service to restore operations. I think that this may be a result of unclosed connections to mongodb from java and also MongoDbFactory do not provide me a function to close a connection. How can I make sure that all connections are closed after a particular session.</p>
  
  <p>This is the code I am using:</p>
  
  <pre><code>package com.####.mongo.configuration;
  
  import com.mongodb.Mongo;
  import org.springframework.context.annotation.Bean;
  import org.springframework.data.mongodb.MongoDbFactory;
  import org.springframework.data.mongodb.core.MongoTemplate;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
  import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
  import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
  import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
  
  @Configuration
  public class SpringMongoFeedConfig {
  
  public @Bean
  MongoDbFactory mongoDbFactory() throws Exception {
      return new SimpleMongoDbFactory(new Mongo(), "feedDatabase");
  }
  
  public @Bean
  MongoTemplate mongoTemplate() throws Exception {
  
      MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
      converter.setTypeMapper(new DefaultMongoTypeMapper(null));
      MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter);
  
  
      return mongoTemplate; 
  } 
  </code></pre>
  
  <p>}</p>
  
  <p>And:</p>
  
  <pre><code>private String insertFeedsToMongo(FeedMongoDTO feedObject, FeedType type) throws UnknownHostException {
      try {
          ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoFeedConfig.class);
          MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
  
          switch (type) {
  
          case FOLLOW:
              mongoOperation.save(feedObject, "feedsByUid");
              break;
  
          case GENERAL:
              mongoOperation.save(feedObject, "allFeeds");
              break;
  
          default:
              break;
          }
  
          return feedObject.getId();
  
      } catch (Exception ex) {
          log.info("insertFeedsToMongo() : mongo Exception - ", ex);
          return null;
      }
  }
  </code></pre>