MongoDBHelper
package util; import com.mongodb.MongoClient; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import java.net.UnknownHostException; import java.util.List; import java.util.Set; public class MongoDBHelper { private static MongoDBHelper uniqueInstance = null; private MongoClient mongoClient; private DB db; private DBCollection coll; private MongoDBHelper(String serverAddress, int port, String dbName, String collectionName ){ try{ mongoClient = new MongoClient(serverAddress, port); db = mongoClient.getDB(dbName); coll = db.getCollection(collectionName); } catch (UnknownHostException e) { e.printStackTrace(); } } public static MongoDBHelper getHelper(){ if(null==uniqueInstance){ uniqueInstance = new MongoDBHelper("localhost",27017,"test","test"); } return uniqueInstance; } public void switchDB(String dbName){ db = mongoClient.getDB(dbName); } public void switchCollection(String collectionName){ coll = db.getCollection(collectionName); } public void switchDBCollection(String dbName, String collectionName){ switchDB(dbName); switchCollection(collectionName); } public void printInfo(){ print("All DBs:"); for (String s : mongoClient.getDatabaseNames()) { print(s+" "); } print("\n\ncurrent DB:"); print("\n\nall collections"); for (String s : db.getCollectionNames()) { print(s+" "); } print("\n\ncurrent collections"); print("\n\nitems in colletion: "); print(String.valueOf(coll.getCount())); } static void print(String out){ System.out.print(out); } }