public <T> T execute(Statement statement) throws BasicException { CompileResult result = this.compiler.compile(statement); for (AbstractRow row : result) { final DBObject bson = row.toBSON(statement.getArgs()); final DB db = this.mongoClient.getDB(row.hasDatabase() ? row.getDatabase() : this.database); final DBCollection table = db.getCollection(row.getTable()); final AbstractRow.Mode mode = row.getMode(); switch (mode) { case insert: table.insert(bson); break; case select: break; case update: break; case delete: table.remove(bson); break; default: throw new RuntimeException("cannot recognize mode: " + mode); } } return null; }
public void remove(String collection, DBObject query) { DBCollection dbCollection = getCollection(collection); dbCollection.remove(query); Jedis jedis = JedisManager.getJedis(); jedis.zrem("expire", query.toString()); jedis.hdel(collection, query.toString()); JedisManager.returnJedis(jedis); }
/** Remove all the expired keys */ public void clearExpired() { Long now = System.currentTimeMillis(); BasicDBObject q = new BasicDBObject("expires", new BasicDBObject("$lt", now).append("$gt", 0)); // remove the match _coll.remove(q); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String deleteProductValue = "false"; try { // Get the form data int productID = Integer.parseInt(request.getParameter("productID")); PrintWriter out = response.getWriter(); DB db = mongo.getDB("FashionFactoryProd"); DBCollection myProducts = db.getCollection("productInfo"); DBCollection myTrending = db.getCollection("myTrending"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("productID", productID); DBCursor cursor = myProducts.find(searchQuery); if (cursor.count() == 0) { deleteProductValue = "false"; request.setAttribute("deleteProductValue", deleteProductValue); RequestDispatcher rd = request.getRequestDispatcher("deleteProduct.jsp"); rd.forward(request, response); } else { int product = 0; while (cursor.hasNext()) { BasicDBObject obj = (BasicDBObject) cursor.next(); product = obj.getInt("productID"); if (product == productID) { myProducts.remove(obj); myTrending.remove(searchQuery); deleteProductValue = "true"; request.setAttribute("deleteProductValue", deleteProductValue); RequestDispatcher rd = request.getRequestDispatcher("deleteProduct.jsp"); rd.forward(request, response); } } } } catch (Exception e) { e.printStackTrace(); } }
@Override public void delete(String className) throws MongoException, UnknownHostException { DB db = MongoDBProvider.getInstance().getDB(); DBCollection coll = db.getCollection("testdata"); BasicDBObject removalQuery = new BasicDBObject(); removalQuery.put("source", className); coll.remove(removalQuery); }
public void delete(String collection, DBObject query) { DBCollection dbCollection = getCollection(collection); dbCollection.remove(query); Jedis jedis = JedisManager.getJedis(); if (jedis.hexists(collection, query.toString())) { jedis.hdel(collection, query.toString(), findOneNoCache(collection, query).toString()); jedis.zrem("expire", collection + "_" + query); } JedisManager.returnJedis(jedis); }
private void removeUser(String user) { DBCollection coll = db().getCollection(M_TOKENS); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query); while (cursor.hasNext()) { DBObject doc = cursor.next(); coll.remove(doc); } }
public void eliminarModificar(UsuarioOD Usuario) { DBCollection coleccionUsuario = conectarMongo(); BasicDBObject query = new BasicDBObject(); query.put("id_u", Usuario.getId_u()); DBCursor cur = coleccionUsuario.find(query); while (cur.hasNext()) { coleccionUsuario.remove(cur.next()); } }
public void eliminar(UsuarioOD Usuario) { DBCollection coleccionUsuario = conectarMongo(); BasicDBObject query = new BasicDBObject(); query.put("nick", Usuario.getNick()); DBCursor cur = coleccionUsuario.find(query); while (cur.hasNext()) { coleccionUsuario.remove(cur.next()); // System.out.println(cur.next()); } }
public void performBatch(List<BatchUnit> rows) { if (logger.isTraceEnabled()) { logger.trace("MongoClientWrapper.performBatch(" + rows + ")"); logger.trace("Batch size to be performed is " + rows.size()); } // List<Future<? extends Number>> pending = new ArrayList<Future<? extends Number>>(); for (BatchUnit row : rows) { SpaceDocument spaceDoc = row.getSpaceDocument(); SpaceTypeDescriptor typeDescriptor = types.get(row.getTypeName()).getTypeDescriptor(); SpaceDocumentMapper<DBObject> mapper = getMapper(typeDescriptor); DBObject obj = mapper.toDBObject(spaceDoc); DBCollection col = getCollection(row.getTypeName()); switch (row.getDataSyncOperationType()) { case WRITE: case UPDATE: col.save(obj); break; case PARTIAL_UPDATE: DBObject query = BasicDBObjectBuilder.start() .add(Constants.ID_PROPERTY, obj.get(Constants.ID_PROPERTY)) .get(); DBObject update = normalize(obj); col.update(query, update); break; // case REMOVE_BY_UID: // Not supported by this implementation case REMOVE: col.remove(obj); break; default: throw new IllegalStateException( "Unsupported data sync operation type: " + row.getDataSyncOperationType()); } } /*long totalCount = waitFor(pending); if (logger.isTraceEnabled()) { logger.trace("total accepted replies is: " + totalCount); }*/ }
@Override public String EliminarJson(String nombreDB, 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 eliminar"); // System.out.println("********************\n"); return "No existe el cliente, no se puede eliminar"; } MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("id", clienteId); collection.remove(searchQuery); return "Cliente eliminado"; }
/** * remove the keys that match the passed criteria in the tags array * * @param tags */ public void clearTags(String tags) { String[] tgs = tags.split(","); for (String t : tgs) { _coll.remove(new BasicDBObject("tags", t)); } }
private void jButton1ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: int flag = 0; try { // TODO add your handling code here: MongoClient mongoClient = new MongoClient("localhost", 27017); db = mongoClient.getDB("Classic_Hangman"); System.out.println("Connected to database successfully!!"); BasicDBObject d = new BasicDBObject(); String movie = jTextField1.getText(); // String genre = jTextField2.getText(); String director = jTextField3.getText(); for (int i = 0; i < director.length(); i++) { if (Character.isDigit(director.charAt(i))) { JOptionPane.showMessageDialog(this, "Invalid director entry!"); flag = 1; break; } } if (movie.equals("") || genre.equals("")) { JOptionPane.showMessageDialog(this, "Empty Field!"); } else { if (flag != 1) { DBCollection coll = db.getCollection("movies"); DBCollection coll1 = db.getCollection("counter"); System.out.println("Collection selected successfully"); BasicDBObject query = new BasicDBObject(); DBObject c = coll1.findOne(); count = ((Number) c.get("count")).intValue(); System.out.println("Count = " + count); // count = (int)c.get("count"); BasicDBObject doc = new BasicDBObject("id", count + 1) .append("name", movie) .append("director", director) .append("genre", genre); coll.insert(doc); System.out.println("Document inserted successfully"); count++; /*DBCursor cursor = coll.find(); int i=1; while (cursor.hasNext()) { System.out.println("Inserted Document: "+i); System.out.println(cursor.next()); i++; }*/ // DBCollection coll1 = db.getCollection("counter"); // System.out.println("Collection selected successfully"); coll1.remove(new BasicDBObject()); BasicDBObject doc1 = new BasicDBObject("count", count); coll1.insert(doc1); /*cursor = coll.find(); BasicDBObject newDocument = new BasicDBObject(); System.out.println(count); newDocument.put("count", count); BasicDBObject searchQuery = new BasicDBObject().append("count", count); coll.update(searchQuery, newDocument);*/ jTextField1.setText(""); // jTextField2.setText(""); jTextField3.setText(""); JOptionPane.showMessageDialog(this, "Record added!"); } } } catch (UnknownHostException ex) { // Logger.getLogger(AdminLogin.class.getName()).log(Level.SEVERE, null, ex); } } // GEN-LAST:event_jButton1ActionPerformed
public static void main(String[] args) { try { // connect to mongoDB, ip and port number Mongo mongo = new Mongo("127.0.0.1", 27017); // get database from MongoDB, // if database doesn't exists, mongoDB will create it automatically DB db = mongo.getDB("yourdb"); // Getting A List Of Collections Set<String> collections = db.getCollectionNames(); for (String s : collections) { System.out.println(s); } // Get collection from MongoDB, database named "yourDB" // if collection doesn't exists, mongoDB will create it automatically DBCollection collection = db.getCollection("yourCollection"); // create a document to store key and value DBObject document = new BasicDBObject(); document.put("id", 1001); document.put("msg", "hello world mongoDB in Java"); // save it into collection named "yourCollection" collection.insert(document); // search query DBObject searchQuery = new BasicDBObject(); searchQuery.put("id", 1001); // query it DBCursor cursor = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursor.hasNext()) { System.out.println("Our collection after putting document here: " + cursor.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // update document (just replase exist - it is normal practise) DBObject updatedDocument = new BasicDBObject(); updatedDocument.put("id", 1001); updatedDocument.put("msg", "hello world mongoDB in Java updated"); collection.update(new BasicDBObject().append("id", 1001), updatedDocument); // query it DBCursor cursorAfterUpdate = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursorAfterUpdate.hasNext()) { System.out.println("Our collection after update: " + cursorAfterUpdate.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // Map to object Message message = new Message(); message.setId((Integer) document.get("id")); message.setMessage((String) document.get("msg")); System.out.println("Id putted in object: " + message.getId()); System.out.println("Message putted in object: " + message.getMessage()); // Remove document from collection DBObject doc = collection.findOne(); // get first document collection.remove(doc); // query it DBCursor cursorAfterDelete = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursorAfterDelete.hasNext()) { System.out.println("Our collection after delete: " + cursorAfterDelete.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // Close connection to db mongo.close(); System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }
/** * Removes the specified username from the database. * * @param username user to be removed * @throws MongoException */ public WriteResult removeUser(String username) { DBCollection c = getCollection("system.users"); return c.remove(new BasicDBObject("user", username)); }
/** * Remove a key from the cache db * * @param key */ public void remove(String key) { _coll.remove(new BasicDBObject("key", key.toLowerCase())); }
public void deleteAllRecords() { DB db = mongoClient.getDB(this.dbName); DBCollection records = db.getCollection("records"); records.remove(new BasicDBObject()); }