List of usage examples for com.mongodb MongoClient getDatabase
public MongoDatabase getDatabase(final String databaseName)
From source file:rmteles.learning.mongodb.examples.week2.spark.HelloWorldMongoDBSparkFreemarkerStyle.java
License:Apache License
public static void main(String[] args) { final Configuration configuration = new Configuration(); configuration.setClassForTemplateLoading(HelloWorldMongoDBSparkFreemarkerStyle.class, "/freemarker"); MongoClient client = new MongoClient(new ServerAddress("localhost", 27017)); MongoDatabase database = client.getDatabase("course"); final MongoCollection<Document> collection = database.getCollection("hello"); collection.drop();//from www . j a v a 2 s. co m collection.insertOne(new Document("name", "MongoDB")); Spark.get("/", (request, response) -> { StringWriter writer = new StringWriter(); try { Template helloTemplate = configuration.getTemplate("hello.ftl"); Document document = collection.find().first(); helloTemplate.process(document, writer); } catch (Exception e) { Spark.halt(500); e.printStackTrace(); } return writer; }); }
From source file:rocks.devonthe.stickychunk.database.MongodbDatabase.java
License:GNU General Public License
public MongodbDatabase() { config = StickyChunk.getInstance().getConfig().database.mongo; databaseName = config.databaseName;// ww w . ja v a2 s . co m host = config.host; port = config.port; MongoClientURI connectionString = new MongoClientURI(String.format("mongodb://%s:%s", host, port)); MongoClient client = new MongoClient(connectionString); database = client.getDatabase(databaseName); }
From source file:rocks.teammolise.myunimol.webapp.issues.SendAdvice.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j av a 2 s . c o m*/ * * @param request * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); MongoClient mongoClient = null; try { if (request.getSession().getAttribute("userInfo") == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); return; } UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo"); String username = userInfo.getUsername(); String password = userInfo.getPassword(); String type = request.getParameter("type"); String other = request.getParameter("other"); String details = request.getParameter("details"); ConfigurationManager confMgr = ConfigurationManagerHandler.getInstance(); String mdburi = confMgr.getMongoDbUri(); int pos = mdburi.lastIndexOf("/"); String dbName = mdburi.substring(pos + 1, mdburi.length()); MongoClientURI uri = new MongoClientURI(mdburi); mongoClient = new MongoClient(uri); MongoDatabase db = mongoClient.getDatabase(dbName); MongoCollection<Document> collection = db.getCollection("advices"); Map<String, Object> userinfo = new HashMap<String, Object>(); userinfo.put("name", userInfo.getName()); userinfo.put("surname", userInfo.getSurname()); userinfo.put("course", userInfo.getCourse()); userinfo.put("department", userInfo.getDepartment()); userinfo.put("totalCFU", userInfo.getTotalCFU()); userinfo.put("username", userInfo.getUsername()); userinfo.put("studentId", userInfo.getStudentId()); userinfo.put("enrolledExams", userInfo.getEnrolledExams()); userinfo.put("registrationDate", userInfo.getRegistrationDate()); userinfo.put("studentClass", userInfo.getStudentClass()); userinfo.put("coursePath", userInfo.getCoursePath()); userinfo.put("courseLength", userInfo.getCourseLength()); Document userInfoDoc = new Document(userinfo); Map<String, Object> advice = new HashMap<String, Object>(); advice.put("type", type); if (other != null) advice.put("other", other); advice.put("details", details); advice.put("userInfo", userInfoDoc); collection.insertOne(new Document(advice)); out.println("{\"result\":\"success\"}"); } catch (Exception ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } finally { out.close(); mongoClient.close(); } }
From source file:rocks.teammolise.myunimol.webapp.issues.SendProblem.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww .j av a 2 s.co m*/ * * @param request * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); MongoClient mongoClient = null; try { if (request.getSession().getAttribute("userInfo") == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); return; } UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo"); String username = userInfo.getUsername(); String password = userInfo.getPassword(); String type = request.getParameter("type"); String other = request.getParameter("other"); String details = request.getParameter("details"); ConfigurationManager confMgr = ConfigurationManagerHandler.getInstance(); String mdburi = confMgr.getMongoDbUri(); int pos = mdburi.lastIndexOf("/"); String dbName = mdburi.substring(pos + 1, mdburi.length()); MongoClientURI uri = new MongoClientURI(mdburi); mongoClient = new MongoClient(uri); MongoDatabase db = mongoClient.getDatabase(dbName); MongoCollection<Document> collection = db.getCollection("problems"); Map<String, Object> userinfo = new HashMap<String, Object>(); userinfo.put("name", userInfo.getName()); userinfo.put("surname", userInfo.getSurname()); userinfo.put("course", userInfo.getCourse()); userinfo.put("department", userInfo.getDepartment()); userinfo.put("totalCFU", userInfo.getTotalCFU()); userinfo.put("username", userInfo.getUsername()); userinfo.put("studentId", userInfo.getStudentId()); userinfo.put("enrolledExams", userInfo.getEnrolledExams()); userinfo.put("registrationDate", userInfo.getRegistrationDate()); userinfo.put("studentClass", userInfo.getStudentClass()); userinfo.put("coursePath", userInfo.getCoursePath()); userinfo.put("courseLength", userInfo.getCourseLength()); Document userInfoDoc = new Document(userinfo); Map<String, Object> problem = new HashMap<String, Object>(); problem.put("type", type); if (other != null) problem.put("other", other); problem.put("details", details); problem.put("userInfo", userInfoDoc); collection.insertOne(new Document(problem)); out.println("{\"result\":\"success\"}"); } catch (Exception ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } finally { out.close(); } }
From source file:sabina.benchmark.MongoDbRepository.java
License:Open Source License
MongoDbRepository(Properties settings) { final int PORT = parseInt(settings.getProperty("mongodb.port")); final String HOST = settings.getProperty("mongodb.host"); final String DATABASE = settings.getProperty("mongodb.database"); final String WORLD = settings.getProperty("mongodb.world.collection"); final String FORTUNE = settings.getProperty("mongodb.fortune.collection"); MongoClient mongoClient = new MongoClient(HOST, PORT); MongoDatabase db = mongoClient.getDatabase(DATABASE); worldCollection = db.getCollection(WORLD); fortuneCollection = db.getCollection(FORTUNE); }
From source file:ServerBatch.BatchDB.java
public static void main(String[] args) throws IOException { //--Keyboard input String str;/*from w ww. ja v a 2s . c o m*/ while (true) { Scanner sc = new Scanner(System.in); System.out.println("Which db ?"); System.out.println("GL for Grand Lyon"); System.out.println("V for Villeurbanne"); System.out.println("L1 for Lyon 1"); str = sc.nextLine(); if (str.equals("V") || str.equals("GL") || str.equals("L1")) break; System.out.println("incorrect value"); } System.out.println("You choose : " + str); Grid grid = new Grid(); String table = ""; switch (str) { case "GL": table = "squaresGL"; System.out.println("Init Grid Grand Lyon"); grid.setLat1(45.56f); grid.setLat2(45.92f); grid.setLong1(4.66f); grid.setLong2(5.07f); grid.setNLat(0.005f); grid.setNLong(0.0075f); grid.initGrid(); break; case "V": table = "squaresV"; System.out.println("Init Grid Villeurbanne"); grid.setLat1(45.75f); grid.setLat2(45.79f); grid.setLong1(4.86f); grid.setLong2(4.92f); grid.setNLat(0.0005f); grid.setNLong(0.00075f); grid.initGrid(); break; case "L1": table = "squaresL1"; System.out.println("Init Grid Lyon 1"); Grid grid1 = new Grid(); grid1.setLat1(45.765f); grid1.setLat2(45.775f); grid1.setLong1(4.830f); grid1.setLong2(4.840f); grid1.setNLat(0.0005f); grid1.setNLong(0.00075f); grid1.initGrid(); Grid grid2 = new Grid(); grid2.setLat1(45.767f); grid2.setLat2(45.775f); grid2.setLong1(4.812f); grid2.setLong2(4.830f); grid2.setNLat(0.0005f); grid2.setNLong(0.00075f); grid2.initGrid(); Grid grid3 = new Grid(); grid3.setLat1(45.773f); grid3.setLat2(45.775f); grid3.setLong1(4.80975f); grid3.setLong2(4.812f); grid3.setNLat(0.0005f); grid3.setNLong(0.00075f); grid3.initGrid(); grid.listSquare.addAll(grid1.listSquare); grid.listSquare.addAll(grid2.listSquare); grid.listSquare.addAll(grid3.listSquare); break; } //--Init Mongo Database client System.out.println("Init MongoDB"); MongoClient mongoClient = new MongoClient(); MongoDatabase db = mongoClient.getDatabase("habitoudb"); //--Init lists of Criterias List<Atm> listAtm = new ArrayList<>(); List<Supermarket> listSuper = new ArrayList<>(); List<Doctor> listDoctor = new ArrayList<>(); List<Kindergarten> listKinder = new ArrayList<>(); List<StationPollution> listStaPol = new ArrayList<>(); //--OSM Parser System.out.println("OSM Parser"); String osmFileName = "data_filtered_GRAND.osm"; //Grand Lyon //String fileName = "data_filtered_ZOOM.osm"; //Zoom Lyon File file = new File(""); String osmPath = file.getAbsolutePath() + "/Data_Osmosis/"; OsmParser osm = new OsmParser(osmfileName, osmPath, listAtm, listSuper, listDoctor, listKinder); osm.parse(); listAtm = osm.getAtms(); listSuper = osm.getSupermarkets(); listDoctor = osm.getDoctors(); listKinder = osm.getKindergartens(); String csvFileName = "station_particules-pm10_4.csv"; String csvPath = file.getAbsolutePath(); AirRhoneParser airParser = new AirRhoneParser(csvPath, csvFileName); listStaPol = airParser.parse(); //--Print informations System.out.println("Number of squares : " + grid.listSquare.size()); System.out.println("Number of atms : " + listAtm.size()); System.out.println("Number of supermarkets : " + listSuper.size()); System.out.println("Number of doctors : " + listDoctor.size()); System.out.println("Number of kindergartens : " + listKinder.size()); //--Calculation of best criterias List<Criteria> listTemp = new ArrayList<>(); for (Square square : grid.listSquare) { //--Init best criterias Atm bestAtmW = new Atm(0f, 0f, 0f, 0f, ""); Atm bestAtmD = new Atm(0f, 0f, 0f, 0f, ""); Supermarket bestSuperW = new Supermarket(0f, 0f, 0f, 0f, ""); Supermarket bestSuperD = new Supermarket(0f, 0f, 0f, 0f, ""); Doctor bestDocW = new Doctor(0f, 0f, 0f, 0f, ""); Doctor bestDocD = new Doctor(0f, 0f, 0f, 0f, ""); Kindergarten bestKinderW = new Kindergarten(0f, 0f, 0f, 0f, ""); Kindergarten bestKinderD = new Kindergarten(0f, 0f, 0f, 0f, ""); StationPollution bestStaPol = new StationPollution(0f, 0f, "", 0f, 0f); for (criteriasEnum criteria : criteriasEnum.values()) { listTemp.clear(); switch (criteria) { case ATM: for (Atm a : listAtm) { listTemp.add((Criteria) a); } listTemp = reduceListForSquare(square, listTemp); for (int modeTransport : modeTransports) { //Criteria bestCTemps = getBestCTimeGoogle(square, listTemp, modeTransport); Criteria bestCTemps = getBestCTimeOsrm(square, listTemp, modeTransport, bestAtmW); switch (modeTransport) { case 0: //Walking bestAtmW.setTime(bestCTemps.getTime()); bestAtmW.setLat(bestCTemps.getLat()); bestAtmW.setLon(bestCTemps.getLon()); bestAtmW.setName(bestCTemps.getName()); bestAtmW.setDistance(bestCTemps.getDistance()); break; case 1: //Driving bestAtmD.setTime(bestCTemps.getTime()); bestAtmD.setLat(bestCTemps.getLat()); bestAtmD.setLon(bestCTemps.getLon()); bestAtmD.setName(bestCTemps.getName()); bestAtmD.setDistance(bestCTemps.getDistance()); break; } } break; case SUPERMARKET: for (Supermarket a : listSuper) { listTemp.add((Criteria) a); } listTemp = reduceListForSquare(square, listTemp); for (int modeTransport : modeTransports) { // Criteria bestCTemps = getBestCTimeGoogle(square, listTemp, modeTransport); Criteria bestCTemps = getBestCTimeOsrm(square, listTemp, modeTransport, bestSuperW); switch (modeTransport) { case 0: //Walking bestSuperW.setTime(bestCTemps.getTime()); bestSuperW.setLat(bestCTemps.getLat()); bestSuperW.setLon(bestCTemps.getLon()); bestSuperW.setName(bestCTemps.getName()); bestSuperW.setDistance(bestCTemps.getDistance()); break; case 1: //Driving bestSuperD.setTime(bestCTemps.getTime()); bestSuperD.setLat(bestCTemps.getLat()); bestSuperD.setLon(bestCTemps.getLon()); bestSuperD.setName(bestCTemps.getName()); bestSuperD.setDistance(bestCTemps.getDistance()); break; } } break; case DOCTOR: for (Doctor d : listDoctor) { listTemp.add((Criteria) d); } listTemp = reduceListForSquare(square, listTemp); for (int modeTransport : modeTransports) { //Criteria bestCTemps = getBestCTimeGoogle(square, listTemp, modeTransport); Criteria bestCTemps = getBestCTimeOsrm(square, listTemp, modeTransport, bestDocW); switch (modeTransport) { case 0: //Walking bestDocW.setTime(bestCTemps.getTime()); bestDocW.setLat(bestCTemps.getLat()); bestDocW.setLon(bestCTemps.getLon()); bestDocW.setName(bestCTemps.getName()); bestDocW.setDistance(bestCTemps.getDistance()); break; case 1: //Driving bestDocD.setTime(bestCTemps.getTime()); bestDocD.setLat(bestCTemps.getLat()); bestDocD.setLon(bestCTemps.getLon()); bestDocD.setName(bestCTemps.getName()); bestDocD.setDistance(bestCTemps.getDistance()); break; } } break; case KINDERGARTEN: for (Kindergarten k : listKinder) { listTemp.add((Criteria) k); } listTemp = reduceListForSquare(square, listTemp); for (int modeTransport : modeTransports) { // Criteria bestCTemps = getBestCTimeGoogle(square, listTemp, modeTransport); Criteria bestCTemps = getBestCTimeOsrm(square, listTemp, modeTransport, bestKinderW); switch (modeTransport) { case 0: //Walking bestKinderW.setTime(bestCTemps.getTime()); bestKinderW.setLat(bestCTemps.getLat()); bestKinderW.setLon(bestCTemps.getLon()); bestKinderW.setName(bestCTemps.getName()); bestKinderW.setDistance(bestCTemps.getDistance()); break; case 1: //Driving bestKinderD.setTime(bestCTemps.getTime()); bestKinderD.setLat(bestCTemps.getLat()); bestKinderD.setLon(bestCTemps.getLon()); bestKinderD.setName(bestCTemps.getName()); bestKinderD.setDistance(bestCTemps.getDistance()); break; } } break; case POLLUTION: bestStaPol = getBestCAir(square, listStaPol); break; } } //--Insertion of square in mongo database InsertMongo im = new InsertMongo(db, table, square, bestAtmW, bestAtmD, bestSuperW, bestSuperD, bestDocW, bestDocD, bestKinderW, bestKinderD, bestStaPol); } }
From source file:soatreefinder.SOATreeFinder.java
public static void loadMongoFromSQL(String sqlQuery, String mongoDBName, String mongoCollName, String mongoCollPrimaryKey) throws SQLException, IOException, FileNotFoundException { propsFile.load(new FileInputStream(System.getProperty("user.dir") + "\\context.properties")); Statement stmt = null;/*from w ww.j a va2 s .c o m*/ String blobString; Map sqlMap = new HashMap(); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress( propsFile.getProperty("mongoHost"), Integer.parseInt(propsFile.getProperty("mongoPort"))))); MongoDatabase db = mongoClient.getDatabase(mongoDBName); MongoCollection coll = db.getCollection(mongoCollName); UpdateOptions upsertOption = new UpdateOptions(); upsertOption.upsert(true); Connection soadb_Connection = DriverManager .getConnection("jdbc:oracle:thin:" + propsFile.getProperty("user") + "/" + propsFile.getProperty("password") + "@//" + propsFile.getProperty("host") + ":" + propsFile.getProperty("port") + "/" + propsFile.getProperty("service")); stmt = soadb_Connection.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { /* The following block of switch statement checks for the sql data type of a given column and puts the appropriate object into the hash map*/ switch (rsmd.getColumnType(i)) { case 12: sqlMap.put(rsmd.getColumnName(i), rs.getString(i)); break; case -9: sqlMap.put(rsmd.getColumnName(i), rs.getString(i)); break; case -15: sqlMap.put(rsmd.getColumnName(i), rs.getString(i)); break; case 16: sqlMap.put(rsmd.getColumnName(i), rs.getBoolean(i)); break; case -7: sqlMap.put(rsmd.getColumnName(i), rs.getByte(i)); break; case 2: sqlMap.put(rsmd.getColumnName(i), rs.getInt(i)); break; case 4: sqlMap.put(rsmd.getColumnName(i), rs.getInt(i)); break; case 6: sqlMap.put(rsmd.getColumnName(i), rs.getFloat(i)); break; case 8: sqlMap.put(rsmd.getColumnName(i), rs.getDouble(i)); break; case 3: sqlMap.put(rsmd.getColumnName(i), rs.getBigDecimal(i)); break; case 1: sqlMap.put(rsmd.getColumnName(i), rs.getString(i)); break; case 91: sqlMap.put(rsmd.getColumnName(i), rs.getDate(i).toString()); break; case 92: sqlMap.put(rsmd.getColumnName(i), rs.getTime(i).toString()); break; case 93: sqlMap.put(rsmd.getColumnName(i), rs.getTimestamp(i).toString()); break; case 2003: sqlMap.put(rsmd.getColumnName(i), rs.getArray(i)); break; case 2004: { Blob blob = rs.getBlob(i); byte[] bdata = blob.getBytes(1, (int) blob.length()); blobString = new String(bdata); sqlMap.put(rsmd.getColumnName(i), blobString); } break; case 2005: sqlMap.put(rsmd.getColumnName(i), rs.getClob(i)); break; default: sqlMap.put(rsmd.getColumnName(i), rs.getString(i)); } } // Upsert sql record into mongo collection coll.updateOne(eq(mongoCollPrimaryKey, sqlMap.get(mongoCollPrimaryKey)), new Document("$set", new Document(sqlMap)), upsertOption); } }
From source file:sockslib.utils.mongo.MongoDBUtil.java
License:Apache License
/** * Connect MongoDB and call callback, close connection at last. * * @param collectionName Collection name. * @param callback Callback//from w w w . j a v a 2 s . c o m * @param <T> The type of value which you want to return. * @return The value which callback returned. */ public <T> T connect(String collectionName, CollectionCallback<T> callback) { MongoClient client = null; T t = null; try { client = getConnectedClient(); MongoDatabase database = client.getDatabase(databaseName); MongoCollection<Document> collection = database.getCollection(collectionName); t = callback.doInCollection(collection); } finally { if (client != null) { client.close(); } } return t; }
From source file:softcons.lab10citysearchv3.MongoDBExamples.java
public static void main(final String[] args) throws ClassNotFoundException, SQLException, IOException { // /*from w w w. j av a 2 s . c o m*/ CSVParser csv = new CSVParser(); dao mydao = new dao(); csv.insertData(); List<Country> coun = csv.getRecord(); // for (Country region:coun){ // if (region.getClass().toString().contains("entities.Region")){ // Region reg=(Region)region; // System.out.println(reg.getCityName()); // } // System.out.println(region.getClass()); // } // 1. Connect to MongoDB instance running on localhost MongoClient mongoClient = Connection.getMongoClient(); // Access database named 'test' MongoDatabase database = mongoClient.getDatabase("citySearchV3"); // Access collection named 'restaurants' MongoCollection collection = database.getCollection("locations"); //mydao.addData(coun, collection); // FindIterable<Document> docList = mydao.findCityByName("\"Vail\"", collection); // FindIterable<Document> docList = mydao.findCityByCoordinates(0, 0, collection); System.out.println("Select An Option"); System.out.println("1: Find Neigbhour cities based on Name"); System.out.println("2: Find Neigbhour cities based on Longtitude and Latitude"); System.out.println("3: Distance between Cities using Longitudes and Latitudes"); System.out.println("4: Exit The Program"); Scanner sc = new Scanner(System.in); int val = sc.nextInt(); switch (val) { case 4: System.exit(0); break; case 3: float longi1, longi2, lati1, lati2; System.out.println("Enter Longitude of First City"); longi1 = sc.nextFloat(); while (Math.abs(longi1) > 180) { System.out.println("Enter the Value Again [-180,180]"); longi1 = sc.nextFloat(); } System.out.println("Enter Latitude of First City"); lati1 = sc.nextFloat(); while (Math.abs(lati1) > 90) { System.out.println("Enter the Value Again [-90,90]"); lati1 = sc.nextFloat(); } System.out.println("Enter Longitude of Second City"); longi2 = sc.nextFloat(); while (Math.abs(longi2) > 180) { System.out.println("Enter the Value Again [-180,180]"); longi2 = sc.nextFloat(); } System.out.println("Enter Latitude of Second City"); lati2 = sc.nextFloat(); while (Math.abs(lati2) > 90) { System.out.println("Enter the Value Again [-90,90]"); lati2 = sc.nextFloat(); } System.out.println("Distance is:"); System.out.println(GreatDistance(longi1, longi2, lati1, lati2) * 6371000); break; case 1: String s; System.out.println("Enter the City Name"); s = sc.nextLine(); // To avoid the empty line, caused by earlier use of Scanner String st = sc.nextLine(); FindIterable<Document> docList = mydao.findCityByName(st, collection); System.out.println("Result Of Longitude and Latitude"); Document tempDoc = docList.first(); Double currentLongitude = tempDoc.getDouble("longitude"); Double currentLatitude = tempDoc.getDouble("latitude"); System.out.println("How Many Nearby locations should be checked?"); int value = sc.nextInt(); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("longitude", new BasicDBObject("$gt", currentLongitude)); searchQuery.put("latitude", new BasicDBObject("$lt", currentLongitude)); docList = collection.find(searchQuery).sort(new BasicDBObject("longitude", 1)); int tempCount = 1; for (Document d : docList) { if (d.getDouble("longitude") < currentLongitude) { continue; } if (tempCount <= value) { System.out.println(d.getString("name")); System.out.println(d.getDouble("longitude")); System.out.println(d.getDouble("latitude")); System.out.print("Distance : "); System.out.println(GreatDistance(currentLongitude, d.getDouble("longitude"), currentLatitude, d.getDouble("latitude"))); tempCount++; } } break; case 2: System.out.println("Enter Longitude:"); float f = sc.nextFloat(); System.out.println("Enter Latitude:"); float f2 = sc.nextFloat(); FindIterable<Document> docListv2 = mydao.findCityByCoordinates(f, f2, collection); Document doc = docListv2.first(); Double currentLongitudev2 = doc.getDouble("longitude"); Double currentLatitudev2 = doc.getDouble("latitude"); System.out.println("How Many Nearby locations should be checked?"); int valuev2 = sc.nextInt(); BasicDBObject searchQueryv2 = new BasicDBObject(); searchQueryv2.put("longitude", new BasicDBObject("$gt", currentLongitudev2)); searchQueryv2.put("longitude", new BasicDBObject("$lt", currentLongitudev2)); docList = collection.find(searchQueryv2).sort(new BasicDBObject("longitude", 1)); int tempCountv2 = 1; for (Document d : docList) { if ((d.getDouble("longitude") - currentLongitudev2) >= -1 && tempCountv2 <= valuev2) { System.out.println(d.getString("name")); System.out.println(d.getDouble("longitude")); System.out.println(d.getDouble("latitude")); System.out.print("Distance : "); System.out.println(GreatDistance(currentLongitudev2, d.getDouble("longitude"), currentLatitudev2, d.getDouble("latitude"))); tempCountv2++; } } break; } System.out.println("Done"); System.exit(0); mongoClient.close(); System.out.println("Done "); }
From source file:Tests.AddElementToCollection.java
public void addToCollection(String jsonString) { MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(MongoCredential.createCredential("admin", "test", "password".toCharArray()))); try {/*from w w w . j a va 2s . c o m*/ for (String databaseName : mongoClient.listDatabaseNames()) { System.out.println("Database: " + databaseName); } MongoDatabase db = mongoClient.getDatabase("test"); MongoCollection coll = db.getCollection("test2"); Document doc = Document.parse(jsonString); coll.insertOne(doc); } finally { mongoClient.close(); } }