I am trying to write a lot of data to MongoDB, in a Java loop. I am getting errors based on the number of connections open.
My theory is that since MongoDB is not transactional, lots of connections can be opened simultaneously. However the Java code is also able to loop very fast, after a certain time the number of loop iterations starts overtaking the number of available connections and Mongo hits a wall.
My code looks like this. I've seen it recommended to not do m.close()
but then you just get the error even faster.
public static void upsert(){
Mongo m = null;
DB db = null;
try {
m = new Mongo("localhost");
db = m.getDB("sempedia"); } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (MongoException e1) { e1.printStackTrace(); }
// create documents
// I am doing an upsert - hence the doc, doc
DBCollection triples;
try {
triples = db.getCollection("triples");
triples.update(doc,doc,true,false);
} catch (MongoException e) { e.printStackTrace(); }
m.close();
}
In my java console I get this error:
WARNING: Exception determining maxBSON size using0 java.net.SocketException: Connection reset
And mongodb gives this error:
Tue Oct 25 22:31:39 [initandlisten] connection refused because too many open connections: 204 of 204
What would be the most elegant way to deal with this issue?