protected <T, V> WriteResult delete(DBCollection dbColl, V id, WriteConcern wc) { WriteResult wr; if (wc == null) wr = dbColl.remove(BasicDBObjectBuilder.start().add(Mapper.ID_KEY, id).get()); else wr = dbColl.remove(BasicDBObjectBuilder.start().add(Mapper.ID_KEY, id).get(), wc); throwOnError(wc, wr); return wr; }
protected void clearMongoDB(MongoDBRepositoryDescriptor descriptor) throws UnknownHostException { MongoClient mongoClient = MongoDBRepository.newMongoClient(descriptor); try { DBCollection coll = MongoDBRepository.getCollection(descriptor, mongoClient); coll.dropIndexes(); coll.remove(new BasicDBObject()); coll = MongoDBRepository.getCountersCollection(descriptor, mongoClient); coll.dropIndexes(); coll.remove(new BasicDBObject()); } finally { mongoClient.close(); } }
protected void doRemove(Exchange exchange) throws Exception { DBCollection dbCol = calculateCollection(exchange); DBObject removeObj = exchange.getIn().getMandatoryBody(DBObject.class); WriteConcern wc = extractWriteConcern(exchange); WriteResult result = wc == null ? dbCol.remove(removeObj) : dbCol.remove(removeObj, wc); Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.remove); // we always return the WriteResult, because whether the getLastError was called or not, // the user will have the means to call it or obtain the cached CommandResult processAndTransferWriteResult(result, exchange); resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN()); }
private void doInserts(final boolean useBulkWriteOperations) { getMorphia().setUseBulkWriteOperations(useBulkWriteOperations); final DBCollection collection = getDs().getCollection(FacebookUser.class); collection.remove(new BasicDBObject()); final int count = 250000; List<FacebookUser> list = new ArrayList<FacebookUser>(count); for (int i = 0; i < count; i++) { list.add(new FacebookUser(i, "User " + i)); } getAds().insert(list, WriteConcern.UNACKNOWLEDGED); Awaitility.await() .atMost(30, TimeUnit.SECONDS) .until( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return collection.count() == count; } }); assertEquals(count, collection.count()); for (FacebookUser user : list) { Assert.assertNotNull(user.getId()); } }
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; }
/** 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 static void removeOldLog(long timeDurationMillis) { long deadlineMillis = System.currentTimeMillis() - timeDurationMillis; if (collLog == null) return; // System.out.println(deadlineMillis); collLog.remove((DBObject) JSON.parse("{ time : {$lt : " + deadlineMillis + "}}")); }
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); }
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(); } }
// Don't drop database, but just clear all data in managed collections (useful for export/import // or during development) protected void clearManagedCollections(Class<?>[] managedEntityTypes) { for (Class<?> clazz : managedEntityTypes) { DBCollection dbCollection = getDBCollectionForType(clazz); if (dbCollection != null) { dbCollection.remove(new BasicDBObject()); logger.debug( "Collection " + dbCollection.getName() + " cleared from " + this.database.getName()); } } }
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); } }
@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); }
// same method as insert except save() is replaced by remove() public void delete(Receipt receipt) { try { BasicDBObject basicDBObject = toBasicDBObject(receipt); DB db = MongoDBCreater.getDB("MyDB"); DBCollection collection = db.getCollection("MyCollection"); collection.remove(basicDBObject); } catch (Exception e) { e.printStackTrace(); } }
/** {@inheritDoc} */ @Override public void delete(String uid) { if (uid == null || uid.isEmpty()) { throw new IllegalArgumentException("Feature identifier cannot be null nor empty"); } if (!exist(uid)) { throw new FeatureNotFoundException(uid); } collection.remove(BUILDER.getFeatUid(uid)); }
@Test public void testRenameAttribute() throws Throwable { logger.debug("Start testRenameAttribute"); try { logger.debug("Create river {}", getRiver()); String script = "ctx.document.score2 = ctx.document.score; delete ctx.document.score;"; super.createRiver( "/test/elasticsearch/plugin/river/mongodb/script/test-mongodb-river-with-script.json", getRiver(), String.valueOf(getMongoPort1()), String.valueOf(getMongoPort2()), String.valueOf(getMongoPort3()), getDatabase(), getCollection(), script, getIndex(), getDatabase()); String mongoDocument = copyToStringFromClasspath( "/test/elasticsearch/plugin/river/mongodb/script/test-simple-mongodb-document.json"); DBObject dbObject = (DBObject) JSON.parse(mongoDocument); WriteResult result = mongoCollection.insert(dbObject); Thread.sleep(wait); String id = dbObject.get("_id").toString(); logger.info("WriteResult: {}", result.toString()); refreshIndex(); ActionFuture<IndicesExistsResponse> response = getNode().client().admin().indices().exists(new IndicesExistsRequest(getIndex())); assertThat(response.actionGet().isExists(), equalTo(true)); SearchResponse sr = getNode() .client() .prepareSearch(getIndex()) .setQuery(fieldQuery("_id", id)) .execute() .actionGet(); logger.debug("SearchResponse {}", sr.toString()); long totalHits = sr.getHits().getTotalHits(); logger.debug("TotalHits: {}", totalHits); assertThat(totalHits, equalTo(1l)); assertThat(sr.getHits().getHits()[0].sourceAsMap().containsKey("score2"), equalTo(true)); mongoCollection.remove(dbObject); } catch (Throwable t) { logger.error("testRenameAttribute failed.", t); t.printStackTrace(); throw t; } finally { super.deleteRiver(); super.deleteIndex(); } }
Boolean Del_MailList(String Time) { try { SendMailColl = SendMailDB.getCollection("Mail_Content"); SendMailColl.remove(new BasicDBObject().append("time", Time)); SendMailColl = SendMailDB.getCollection(Time); SendMailColl.drop(); return true; } catch (Exception e) { return false; } }
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()); } }
Boolean Del_User(String Id, String Pw) { try { m.dropDatabase(Id); UserColl = UserDB.getCollection("User"); BasicDBObject doc; doc = MakeUserDocument(Id, Pw); UserColl.remove(doc); return true; } catch (Exception e) { return false; } }
@Test public void testRemove() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.remove(new BasicDBObject("_id", 2)); assertEquals(null, collection.findOne(new BasicDBObject("_id", 2))); }
private void removeRecords() { Mongo mongo; try { mongo = new Mongo(MONGO_DB_COLLECTION, MONGO_DB_PORT); DB db = mongo.getDB(MONGO_DB_NAME); DBCollection collection = db.getCollection(MONGO_DB_COLLECTION); collection.remove(new BasicDBObject()); } catch (UnknownHostException e) { e.printStackTrace(); } }
public boolean delete(String id) { MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds015909.mlab.com:15909/lab8_ase"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection Users = db.getCollection("userdata"); BasicDBObject query = new BasicDBObject(); ObjectId oid = new ObjectId(id); query.put("_id", oid); Users.remove(query); client.close(); return true; }
public <T> WriteResult delete(Query<T> query, WriteConcern wc) { QueryImpl<T> q = (QueryImpl<T>) query; DBCollection dbColl = q.getCollection(); // TODO remove this after testing. if (dbColl == null) dbColl = getCollection(q.getEntityClass()); WriteResult wr; if (q.getSortObject() != null || q.getOffset() != 0 || q.getLimit() > 0) throw new QueryException("Delete does not allow sort/offset/limit query options."); if (q.getQueryObject() != null) if (wc == null) wr = dbColl.remove(q.getQueryObject()); else wr = dbColl.remove(q.getQueryObject(), wc); else if (wc == null) wr = dbColl.remove(new BasicDBObject()); else wr = dbColl.remove(new BasicDBObject(), wc); throwOnError(wc, wr); return wr; }
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 static void main(String[] args) throws TasteException, UnknownHostException, MongoException { model = new MongoDBDataModel( "127.0.0.1", 27017, "right-channel", "ratings", false, false, null, "user_id", "movie_id", "rating", MongoDBDataModel.DEFAULT_MONGO_MAP_COLLECTION); ItemSimilarity similarity = new PearsonCorrelationSimilarity(model); Recommender recommender = new BiasedItemBasedRecommender(model, similarity); IDRescorer rescorer = new OverallRescorer(); List<RecommendedItem> recommendations = recommender.recommend( Long.parseLong( model.fromIdToLong( new ObjectId("518ce9df4597b5adead4b61d").toStringMongod(), false)), 1000, rescorer); Mongo mongoDB = new Mongo("127.0.0.1", 27017); DB db = mongoDB.getDB("right-channel"); DBCollection recommendationCollection = db.getCollection("recommendations"); BasicDBObject document = new BasicDBObject(); document.put("user_id", new ObjectId("518ce9df4597b5adead4b61d")); recommendationCollection.remove(document); for (RecommendedItem recommendation : recommendations) { long movieIdLong = recommendation.getItemID(); String movieIdString = model.fromLongToId(movieIdLong); ObjectId movieIdObject = new ObjectId(movieIdString); double rating = recommendation.getValue(); BasicDBObject prediction = new BasicDBObject(); Object userIdObject = new ObjectId("518ce9df4597b5adead4b61d"); prediction.put("user_id", userIdObject); prediction.put("movie_id", movieIdObject); prediction.put("rating", rating); recommendationCollection.insert(prediction); System.out.println(rating); } }
@DELETE @Path("/delete/{workspaceid}/document/{documentid}") @Produces("application/json") public String deleteDocument( @PathParam("workspaceid") String workspaceID, @PathParam("documentid") String documentID) { DB db = m.getDB(Tokens.WORKSPACE_DATABASE); DBCollection coll = db.getCollection(workspaceID); DBObject deleteme = findbyIDquery(coll, documentID); coll.remove(deleteme); BasicDBObject bo = new BasicDBObject(); bo.append("status", "document= " + workspaceID + " deleted"); // System.out.println(bo.toString()); return bo.toString(); }
public boolean delRecord(BasicDBObject conditionDBObject, String collectionName) { try { DBCollection collection = getCollection(collectionName); WriteResult result = collection.remove(conditionDBObject, writeConcernWithTimeOut); return processResult(result); } catch (Exception e) { logger.error( "BaseMongoDAO.delRecord删除数据时发生异常,入参collectionName=" + collectionName + "; conditionDBObject=" + conditionDBObject, e); } return false; }
public boolean execute(String title) { BooksConnectionProvider booksConn = new BooksConnectionProvider(); DBCollection booksCollection = booksConn.getCollection(); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("title", title); DBCursor cursor = booksCollection.find(searchQuery); while (cursor.hasNext()) { booksCollection.remove(searchQuery); } return true; }
// 删除指定id的语料 public void deletecorpus() throws UnknownHostException { String message = "请输入要读取的文本编号!"; long idm = 1; Object obj = JOptionPane.showInputDialog(null, message, idm); String obj1 = (String) obj; if (obj1 == null) { return; } long id1 = Long.parseLong(obj1); MongoClient mc = null; DB db = null; mc = new MongoClient("127.0.0.1", 27017); db = mc.getDB("corpus"); DBCollection textsave = null; if (Readcorpustype == "熟语料") { textsave = db.getCollection("ripe"); } else if (Readcorpustype == "生语料") { textsave = db.getCollection("raw"); } else if (Readcorpustype == null) { JOptionPane.showMessageDialog(null, "请在帮助菜单中设置语料类型!"); return; } DBCursor cursor = textsave.find(); Gson gson = new Gson(); long countoftextsave = textsave.getCount(); long counti = 0; long uid = -1; while (cursor.hasNext()) { DBObject st = cursor.next(); Savetext u = gson.fromJson(st.toString(), Savetext.class); counti++; uid = u.id; if (uid == id1) { ReadDbobject = cursor.curr(); textsave.remove(ReadDbobject); System.out.println("删除成功"); break; } else if (uid != id1) { continue; } } if ((counti == countoftextsave) && (uid != id1)) { JOptionPane.showMessageDialog(null, "wrong id!"); return; } }
public static Result deleteTask(Long id) { BasicDBObject query = new BasicDBObject(); query.put("id", id); DBCollection coll = db.getCollection("tasklist"); Object cursor = coll.find(query); try { while (((DBCursor) cursor).hasNext()) { DBObject dbObject = ((DBCursor) cursor).next(); coll.remove(dbObject); } } finally { ((DBCursor) cursor).close(); } return tasks(); }