public static void updateMongoDB( String mongoHost, int mongoPort, String mongoDb, String flightsCol, String legsCollection) { MongoClient mongoClient = new MongoClient(mongoHost, mongoPort); MongoDatabase db = mongoClient.getDatabase(mongoDb); FindIterable<Document> iterable = db.getCollection(flightsCol).find(); db.getCollection(legsCollection).createIndex(new Document("flightID", 1)); db.getCollection(legsCollection).createIndex(new Document("departureAirport._id", 1)); db.getCollection(legsCollection).createIndex(new Document("arrivalAirport._id", 1)); db.getCollection(legsCollection).createIndex(new Document("effectiveDate", 1)); db.getCollection(legsCollection).createIndex(new Document("discontinuedDate", 1)); iterable.forEach( new Block<Document>() { public void apply(final Document document) { try { List<FlightLeg> legs = FlightToLegs.getInstance().getLegsFromFlightRecord(document); for (FlightLeg leg : legs) { FlightLegDAO legDAO = new FlightLegDAOMongoImpl(); legDAO.setHost(mongoHost); legDAO.setPort(mongoPort); legDAO.setDB(mongoDb); legDAO.create(leg); } } catch (Exception e) { e.printStackTrace(); } } }); System.out.println("Done"); mongoClient.close(); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds019028.mlab.com:19028/asedb"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("UserRecords"); BasicDBObject query = new BasicDBObject(); String firstname = request.getParameter("FirstName"); String lastname = request.getParameter("LastName"); String email = request.getParameter("email"); String password = request.getParameter("EnterPassword"); String confpasswd = request.getParameter("ConfirmPassword"); query.put("First Name", firstname); query.put("Last Name", lastname); query.put("Email", email); System.out.println(email); if (password == confpasswd) { query.put("Password", password); } else { } DBCursor docs = users.find(query); response.getWriter().write(docs.toArray().toString()); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); System.out.println("Insert doget"); }
@Override public String IngresarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); // Ya existe if (ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("Ya existe cliente, error no se igresa el Json"); // System.out.println("********************\n"); return "Ya existe cliente, error no se igresa el Json"; } // no existe el cliente DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); document.put("id", clienteId); DBObject object = (DBObject) JSON.parse(json); document.put("json", object); // document.put("json",json); collection.insert(document); return "Ok"; }
public static void main(String[] args) { System.setProperty("javax.net.ssl.trustStore", args[0]); System.setProperty("javax.net.ssl.trustStorePassword", args[1]); MongoClientOptions.Builder options = builder().sslEnabled(true).sslInvalidHostNameAllowed(true); String uri = "mongodb://127.0.0.1:27017/"; MongoClientURI connectionString = new MongoClientURI(uri, options); MongoClient mongoClient = new MongoClient(connectionString); // with username and password char[] pwd = "mypasswrd!".toCharArray(); MongoCredential credential = MongoCredential.createCredential( "myadmin", "admin", pwd); // user "myadmin" on admin database List<MongoCredential> credentials = Collections.singletonList(credential); List<ServerAddress> hosts = Arrays.asList( new ServerAddress("mongodb01.host.dblayer.com:10054"), new ServerAddress("mongodb02.host.1.dblayer.com:10071")); mongoClient = new MongoClient(hosts, credentials, options.build()); MongoDatabase foxtrot = mongoClient.getDatabase("foxtrot"); MongoIterable<String> collectionNames = foxtrot.listCollectionNames(); }
public static void main(String[] args) throws IOException { String term = JOptionPane.showInputDialog( "Welcome to our knock-off search engine! \nPlease enter a term to search:"); while (term == null || term.isEmpty()) { term = JOptionPane.showInputDialog( "You didn't input anything! \nPlease enter a term to search: "); } MongoClient mongoClient = new MongoClient("localhost", 27017); System.out.println("Establishing connection..."); // Get the connection. DB db = mongoClient.getDB("crawler"); DBCollection table = db.getCollection("urlpages"); System.out.println("Connected to MongoDB!"); db.getCollection("pagerank").drop(); Ranking ranker = new Ranking(db); ranker.link_analysis(); ranker.TFIDF(term); run(term, db); JOptionPane.showMessageDialog( null, "Search is completed! \nPlease refer to 'C:\\data\\search_results.json' for the result."); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("dotNotationTest"); lines.drop(); Random rand = new Random(); for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", rand.nextInt(90) + 10) .append("y", rand.nextInt(90) + 10))); } QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50); DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
public static void main(String[] args) throws Exception { MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection("collection"); lanciaTest(coll); }
// Steps: // 1. Install unlimited strength encryption jar files in jre/lib/security // (e.g. http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html) // 2. run kinit // 3. Set system properties, e.g.: // -Djava.security.krb5.realm=10GEN.ME -Djavax.security.auth.useSubjectCredsOnly=false // -Djava.security.krb5.kdc=kdc.10gen.me // auth.login.defaultCallbackHandler=name of class that implements // javax.security.auth.callback.CallbackHandler // You may also need to define realms and domain_realm entries in your krb5.conf file (in /etc by // default) public static void main(String[] args) throws UnknownHostException, InterruptedException { // Set this property to avoid the default behavior where the program prompts on the command line // for username/password Security.setProperty("auth.login.defaultCallbackHandler", "DefaultSecurityCallbackHandler"); String server = args[0]; String user = args[1]; String dbName = args[2]; MongoClient mongo = new MongoClient( new MongoClientAuthority( new ServerAddress(server), new MongoClientCredentials(user, MongoClientCredentials.GSSAPI_MECHANISM)), new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build()); DB testDB = mongo.getDB(dbName); System.out.println("Find one: " + testDB.getCollection("test").findOne()); System.out.println("Count: " + testDB.getCollection("test").count()); WriteResult writeResult = testDB.getCollection("test").insert(new BasicDBObject()); System.out.println("Write result: " + writeResult); System.out.println(); System.out.println("Count: " + testDB.getCollection("test").count()); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuilder buffer = new StringBuilder(); BufferedReader reader = request.getReader(); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } String data = buffer.toString(); System.out.println(data); JSONObject params = new JSONObject(data); String email = (String) params.get("email"); String password = (String) params.get("password"); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds011459.mlab.com:11459/farmville"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("logindetails"); BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", new BasicDBObject().append("password", password)); BasicDBObject searchQuery = new BasicDBObject().append("email", email); WriteResult result = users.update(searchQuery, newDocument); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); response.getWriter().write(result.toString()); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds037824.mongolab.com:37824/aseproject"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("users"); BasicDBObject query = new BasicDBObject(); query.put("name", request.getParameter("name")); query.put("password", request.getParameter("password")); DBCursor docs = users.find(); response.getWriter().write(docs.toArray().toString()); /*JSONObject obj=new JSONObject(); obj.put("message", "Hello World"); response.getWriter().write(obj.toString()); */ response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); }
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase("week5"); MongoCollection<Document> col = db.getCollection("grads"); Document unwind = new Document("$unwind", "$scores"); Document quizFilter = new Document( "$match", new Document( "$or", asList( new Document("scores.type", "exam"), new Document("scores.type", "homework")))); Document groupByClassAndStudent = new Document( "$group", new Document() .append( "_id", new Document().append("class", "$class_id").append("student", "$student_id")) .append("avg_per_student", new Document("$avg", "$scores.score"))); Document groupByClass = new Document( "$group", new Document() .append("_id", "$_id.class") .append("avg_per_class", new Document("$avg", "$avg_per_student"))); Document sort = new Document("$sort", new Document("avg_per_class", 1)); MongoCursor<Document> cursor = col.aggregate(asList(unwind, quizFilter, groupByClassAndStudent, groupByClass, sort)) .iterator(); showColl(cursor); }
public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB feederDB = mongo.getDB("feeder"); DBCollection products = feederDB.getCollection("products"); System.out.println(products.find().size()); mongo.close(); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("DotNotationTest"); lines.drop(); Random rand = new Random(); // insert 10 lines with random start and end points for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)) .append("end", new BasicDBObject("x", rand.nextInt(90) + 10)) .append("y", rand.nextInt(90) + 10)); } // Filter by x coordinate using . notation QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50); // Dot notation is also available for field selection DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
public static void updateSQLDB(String mongoHost, int mongoPort, String mongoDb) { MongoClient mongoClient = new MongoClient(mongoHost, mongoPort); MongoDatabase db = mongoClient.getDatabase(mongoDb); FindIterable<Document> iterable = db.getCollection("flights").find(); iterable.forEach( new Block<Document>() { public void apply(final Document document) { List<FlightLeg> legs = FlightToLegs.getInstance().getLegsFromFlightRecord(document); for (FlightLeg leg : legs) { FlightLegDAO legDAO = new FlightLegDAOJDBCImpl(); int result = legDAO.create(leg); if (result == 0) { System.out.println( "[" + result + "]: ERROR Leg Creation:" + leg.getDepartureAirportCode() + "->" + leg.getArrivalAirportCode() + " DepartureUTC: " + leg.getDepartureTimeUTC() + " ArrivalUTC: " + leg.getArrivalTimeUTC()); System.exit(0); } } } }); System.out.println("Done"); mongoClient.close(); }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds047752.mlab.com:47752/ase_lab7"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("users"); BasicDBObject query = new BasicDBObject().append("username", "Ram"); query.put("name", "Ram"); // request.getParameter("name")); query.put("password", "password"); // request.getParameter("password")); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("name", "SreeRam"); users.update(query, newDocument); DBCursor docs = users.find(query); response.getWriter().write(docs.toArray().toString()); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); }
public static void main(String[] args) throws IOException { DB db = null; try { cargarParametros(); MongoClient mongoClient = new MongoClient(); db = mongoClient.getDB(BaseDeDatos); // System.out.println("Connect to database successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } DBCollection documentos = db.getCollection(ColeccionIndice); while (true) { BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); String consulta = lector.readLine().toLowerCase(); BasicDBObject palabra = new BasicDBObject("palabra", consulta); DBCursor cursor; cursor = documentos.find(palabra); if (cursor.count() == 0) { System.out.println("No se encuentra resultado"); } else { int cantidad_respuestas = cursor.count(); BasicDBObject respuesta = (BasicDBObject) cursor.one().get("documentos"); for (int i = 0; i < respuesta.size(); i++) { System.out.println(respuesta.get("Documento-" + Integer.toString(i))); } } } }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findCriteriaTest"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert( new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100))); } QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(90); // DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", // 10).append("$lt", 90)); System.out.println("\nCount:"); long count = collection.count(builder.get()); System.out.println(count); System.out.println("\nFind all:"); DBCursor cursor = collection.find(builder.get()); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
public void getCommitCount() throws Exception { MongoClient mongoClient = new MongoClient(MongoInfo.getMongoServerIp(), 27017); MongoDatabase database = mongoClient.getDatabase("ghcrawlerV3"); FindIterable<Document> issueIterable = database.getCollection("commitnumber").find(); Connection connection = MysqlInfo.getMysqlConnection(); connection.setAutoCommit(false); JsonParser parser = new JsonParser(); for (Document document : issueIterable) { String json = document.toJson(); JsonObject repoJsonObject = parser.parse(json).getAsJsonObject(); int commit = repoJsonObject.get("commitnumber").getAsInt(); String full_name = repoJsonObject.get("fn").getAsString(); System.out.println(full_name); String sql = "update repotest set commit = ? where full_name = ?"; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setInt(1, commit); stmt.setString(2, full_name); stmt.execute(); } connection.commit(); connection.close(); mongoClient.close(); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(new ServerAddress("localhost", 27017)); final DB db = client.getDB("course"); Spark.get( new Route("/") { @Override public Object handle(Request request, Response response) { DBCollection users = db.getCollection("user"); DBObject user = users.findOne(); StringWriter writer = new StringWriter(); Configuration configuration = new Configuration(); configuration.setClassForTemplateLoading( HelloWorldMongoDBSparkFreemarkerStyle.class, "/"); try { Template template = configuration.getTemplate("hello.ftl"); template.process(user, writer); } catch (Exception e) { halt(100); e.printStackTrace(); } return writer; } }); }
public void getIssueAndPull() throws Exception { MongoClient mongoClient = new MongoClient(MongoInfo.getMongoServerIp(), 27017); MongoDatabase database = mongoClient.getDatabase("ghcrawlerV3"); FindIterable<Document> issueIterable = database.getCollection("issueandpull").find(); Connection connection = MysqlInfo.getMysqlConnection(); connection.setAutoCommit(false); String sql = "update repotest set open_issues = ?,closed_issues = ?,open_pull=?,closed_pull=? where full_name = ?"; PreparedStatement stmt = connection.prepareStatement(sql); JsonParser parser = new JsonParser(); for (Document document : issueIterable) { String json = document.toJson(); JsonObject repoIssue = parser.parse(json).getAsJsonObject(); int openIssue = repoIssue.get("openissue").getAsInt(); int closedIssue = repoIssue.get("closedissue").getAsInt(); int openPull = repoIssue.get("openpull").getAsInt(); int closedPull = repoIssue.get("closedpull").getAsInt(); String repoName = repoIssue.get("fn").getAsString(); System.out.println(repoName); stmt.setInt(1, openIssue); stmt.setInt(2, closedIssue); stmt.setInt(3, openPull); stmt.setInt(4, closedPull); stmt.setString(5, repoName); stmt.execute(); } connection.commit(); connection.close(); mongoClient.close(); }
@Override public void run() { MongoProfile profile = options.getProfile(); MongoClient mongo = null; DBCursor cursor = null; try { mongo = new MongoClient(profile.getAddress(), profile.getCredentials()); DB db = mongo.getDB(options.getDatabase()); DBCollection col = db.getCollection(options.getCollection()); cursor = col.find(); while (cursor.hasNext()) { DBObject doc = cursor.next(); Map<String, Object> m = convert(doc); pushPipe(new Row(m)); } } catch (Throwable t) { slog.error("araqne logdb mongo: cannot run mongo.find", t); } finally { if (cursor != null) cursor.close(); if (mongo != null) mongo.close(); } }
public static void main(String[] args) throws UnknownHostException { System.out.println("Start Testing"); MongoClient client = new MongoClient(new ServerAddress("192.168.0.14", 27017)); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findTestFromJava"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", new Random().nextInt(100))); } System.out.println("Find one:"); DBObject one = collection.findOne(); System.out.println("one = " + one); System.out.println("\nFind all:"); DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println("cursor = " + cur); } } finally { cursor.close(); } System.out.println("\nFind Count:"); long count = collection.count(); System.out.println("count = " + count); }
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase("course"); MongoCollection<Document> collection = db.getCollection("deleteTest"); collection.drop(); for (int idx = 1; idx <= 8; idx++) { collection.insertOne(new Document("_id", idx)); } System.out.println("Before any deletes"); List<Document> docs = collection.find().into(new ArrayList<Document>()); for (Document doc : docs) { Helper.prettyPrintJSON(doc); } // delete 2,3,4 collection.deleteMany(and(gte("_id", 2), lt("_id", 5))); System.out.println("removed gte2 lt5"); docs = collection.find().into(new ArrayList<Document>()); for (Document doc : docs) { Helper.prettyPrintJSON(doc); } collection.deleteOne(eq("_id", 8)); System.out.println("Removed id 8"); docs = collection.find().into(new ArrayList<Document>()); for (Document doc : docs) { Helper.prettyPrintJSON(doc); } }
/** * if hourlyjob has completed,item will insert to repository db.and partial file will delete, * dailydb will delete. * * @throws UnknownHostException */ @Test public void t2() throws UnknownHostException { MongoClient mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT); DB dailyDb = mongoClient.getDB(dailyDbName); DBCollection hourlyCol = dailyDb.getCollection(AppConstants.MongoNames.HOURLY_JOB_COL_NAME); // must drop,or complete status detect will wrong. hourlyCol.drop(); for (int idx = 24; idx > 12; idx--) { DBObject dbo = new BasicDBObject() .append(AppConstants.MongoNames.HOURLY_JOB_NUMBER_KEY, idx + "") .append(AppConstants.MongoNames.HOURLY_JOB_STATUS_KEY, "end"); hourlyCol.insert(dbo); } new DailyCopyWorkVerticle.DailyCopyProcessor( mongoClient, dailyDbName, repositoryDbName, dailyPartialDir, new JsonObject().putNumber("dailydbreadgap", 1000)) .process(); mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT); DB db = mongoClient.getDB(repositoryDbName); DBCollection col = db.getCollection(AppConstants.MongoNames.PAGE_VISIT_COL_NAME); Assert.assertEquals(10005, col.count()); Assert.assertFalse(Files.exists(Paths.get(dailyPartialDir, dailyDbName))); }
public static DB createDbMock() { DB db = mock(DB.class); MongoClient mongoClient = mock(MongoClient.class); when(mongoClient.getDB(Mockito.anyString())).thenReturn(db); MongoDBConnection.setMongoClient(mongoClient); return db; }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); // JSONObject object = new JSONObject(); // object.put("message", "Hello World"); // response.getWriter().write(object.toString()); response.getWriter().write("Read Users<br /><br />"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds031611.mongolab.com:31611/testbeerdb"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection songs = db.getCollection("users"); DBCursor docs = songs.find(); response.getWriter().write(docs.toArray().toString()); doPost(request, response); }
@Override public String ActualizarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub if (!ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede actualizar"); // System.out.println("********************\n"); return "No existe el cliente, no se puede actualizar"; } MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); DBObject object = (DBObject) JSON.parse(json); document.put("id", clienteId); document.put("json", object); BasicDBObject query = new BasicDBObject().append("id", clienteId); collection.findAndModify(query, document); return "Cliente actualizado"; }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB courseDB = client.getDB("course"); DBCollection list = courseDB.getCollection("DotNotationTest"); list.drop(); Random random = new Random(); for (int i = 0; i < 10; i++) { list.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10))); } DBCursor cursor = list.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2).limit(10); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
@Override public String Json(String nombreDB, int clienteId) throws UnknownHostException, JSONException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject query = new BasicDBObject(); query.put("id", clienteId); DBCursor cursor = collection.find(query); if (cursor.size() == 0) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede ingresar json"); // System.out.println("********************\n"); return "No existe el cliente, no se puede ingresar json"; } // Existe el cliente DBObject objeto = (DBObject) cursor.next(); DBObject json = (DBObject) objeto.get("json"); // DBObject j = JSON.parse(json.toString()); JSONObject aj = new JSONObject(json.toString()); return aj.toString(); }
public EMSMongoClient() throws IOException { Properties config = new Properties(); InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties"); config.load(in); MongoClient client; List<ServerAddress> serverAddresses = Arrays.asList( new ServerAddress( config.getProperty("mongo_host"), Integer.parseInt(config.getProperty("mongo_port")))); if (config.containsKey("mongo_user") && config.containsKey("mongo_password")) { MongoCredential credential = MongoCredential.createMongoCRCredential( config.getProperty("mongo_user"), config.getProperty("mongo_db"), config.getProperty("mongo_password").toCharArray()); client = new MongoClient(serverAddresses, Arrays.asList(credential)); } else { client = new MongoClient(serverAddresses); } DB db = client.getDB(config.getProperty("mongo_db")); this.collection = db.getCollection("sessions"); }