List of usage examples for com.mongodb DBCollection remove
public WriteResult remove(final DBObject query)
From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java
License:Apache License
public static WriteResult delete(PersistenceContext context, MetaClass metadata, DBObject deleteObject) { long start = System.currentTimeMillis(); WriteResult writeResult = null;// w w w. j ava2s. c om String msg = "success"; DBCollection dbCollection = context.getDBCollection(metadata); try { writeResult = dbCollection.remove(deleteObject); } catch (Throwable t) { msg = t.getMessage(); handleMongoException(t); } finally { logMongoAction(context, "delete", start, dbCollection, deleteObject, null, null, null, msg); } return writeResult; }
From source file:com.edduarte.argus.document.DocumentCollection.java
License:Apache License
/** * Removes the specified document from the local database. *//*w w w .j av a2s .c o m*/ public void remove(String url) { Document d = get(url); if (d != null) { d.destroy(); DBCollection collection = documentsDB.getCollection(collectionName); collection.remove(d); } documentsCache.remove(url); }
From source file:com.edgytech.umongo.CollectionPanel.java
License:Apache License
public void remove(final ButtonBase button) { final DBCollection col = getCollectionNode().getCollection(); final BasicDBObject tmp = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.removeQuery)).getDBObject(); final BasicDBObject doc = tmp != null ? tmp : new BasicDBObject(); if (doc.isEmpty()) { ConfirmDialog confirm = (ConfirmDialog) getBoundUnit(Item.rmAllConfirm); if (!confirm.show()) { return; }/* w w w . j av a 2 s. c o m*/ } new DbJob() { @Override public Object doRun() throws IOException { return col.remove(doc); } @Override public String getNS() { return col.getFullName(); } @Override public String getShortName() { return "Remove"; } @Override public DBObject getRoot(Object result) { return new BasicDBObject("query", doc); } @Override public ButtonBase getButton() { return button; } }.addJob(); }
From source file:com.edgytech.umongo.CollectionPanel.java
License:Apache License
public void removeTagRange(ButtonBase button) { final DB config = getCollectionNode().getCollection().getDB().getSisterDB("config"); final DBCollection col = config.getCollection("tags"); final String ns = getCollectionNode().getCollection().getFullName(); String value = getComponentStringFieldValue(Item.tagRangeList); BasicDBObject range = (BasicDBObject) JSON.parse(value); final DBObject min = (DBObject) range.get("min"); final DBObject doc = new BasicDBObject("_id", new BasicDBObject("ns", ns).append("min", min)); new DbJob() { @Override/*from ww w.jav a 2 s . c om*/ public Object doRun() { return col.remove(doc); } @Override public String getNS() { return ns; } @Override public String getShortName() { return "Remove Tag Range"; } @Override public DBObject getRoot(Object result) { BasicDBObject root = new BasicDBObject("doc", doc); return root; } @Override public void wrapUp(Object res) { super.wrapUp(res); refreshTagRangeList(); } }.addJob(); }
From source file:com.edgytech.umongo.DocumentMenu.java
License:Apache License
public void remove(ButtonBase button) { final DocView dv = (DocView) (UMongo.instance.getTabbedResult().getSelectedUnit()); TreeNodeDocument node = (TreeNodeDocument) dv.getSelectedNode().getUserObject(); final DBObject doc = node.getDBObject(); if (dv.getDBCursor() == null) { // local data Tree tree = dv.getTree();//www. j a v a2 s .com tree.removeChild(node); tree.structureComponent(); tree.expandNode(tree.getTreeNode()); return; } // go by _id if possible final DBObject query = doc.containsField("_id") ? new BasicDBObject("_id", doc.get("_id")) : doc; final DBCollection col = dv.getDBCursor().getCollection(); new DbJob() { @Override public Object doRun() { return col.remove(query); } @Override public String getNS() { return col.getFullName(); } @Override public String getShortName() { return "Remove"; } @Override public void wrapUp(Object res) { super.wrapUp(res); dv.refresh(null); } @Override public DBObject getRoot(Object result) { return query; } }.addJob(); }
From source file:com.edgytech.umongo.RouterPanel.java
License:Apache License
public void regenConfigDB(ButtonBase button) throws UnknownHostException { MongoClient cmongo = getRouterNode().getMongoClient(); String servers = getStringFieldValue(Item.regenServers); final String db = getStringFieldValue(Item.regenDB); final String col = getStringFieldValue(Item.regenCollection); final String ns = db + "." + col; final DBObject shardKey = ((DocBuilderField) getBoundUnit(Item.regenShardKey)).getDBObject(); final boolean unique = getBooleanFieldValue(Item.regenKeyUnique); final BasicDBObject result = new BasicDBObject(); result.put("ns", ns); result.put("shardKey", shardKey); result.put("unique", unique); // create direct mongo for each replica set String[] serverList = servers.split("\n"); List<ServerAddress> list = new ArrayList<ServerAddress>(); String txt = ""; String primaryShard = null;/*w ww . ja v a 2 s . co m*/ final BasicDBObject shardList = new BasicDBObject(); HashMap<MongoClient, String> mongoToShard = new HashMap<MongoClient, String>(); sLoop: for (String server : serverList) { server = server.trim(); String[] tokens = server.split("/"); if (tokens.length != 2) { new InfoDialog(null, "Error", null, "Server format must be like 'hostname:port/shard', one by line") .show(); return; } server = tokens[0]; String shard = tokens[1]; if (primaryShard == null) { primaryShard = shard; } ServerAddress addr = new ServerAddress(server); // filter out if replset already exists for (MongoClient replset : mongoToShard.keySet()) { if (replset.getServerAddressList().contains(addr)) { continue sLoop; } } list.clear(); list.add(addr); MongoClient mongo = new MongoClient(list); // UMongo.instance.addMongoClient(mongo, null); // make request to force server detection mongo.getDatabaseNames(); mongoToShard.put(mongo, shard); String desc = null; if (!mongo.getDatabaseNames().contains(db) || !mongo.getDB(db).getCollectionNames().contains(col)) { desc = "Collection not present!"; } else { // try to see if shard key has index DBObject index = mongo.getDB(db).getCollection("system.indexes") .findOne(new BasicDBObject("key", shardKey)); if (index != null) { desc = "shard key found"; } else { desc = "shard key NOT found!"; } } txt += mongo.toString() + " shard=" + shard + " - " + desc + "\n"; BasicDBObject shardObj = new BasicDBObject("servers", mongo.toString()); shardObj.put("status", desc); if (shardList.containsField(shard)) { new InfoDialog(null, "Error", null, "Duplicate Shard name " + shard).show(); return; } shardList.put(shard, shardObj); } result.put("shards", shardList); FormDialog dia = (FormDialog) getBoundUnit(Item.regenRSList); dia.setStringFieldValue(Item.regenRSListArea, txt); if (!dia.show()) { return; } DB config = cmongo.getDB("config"); // add database record BasicDBObject doc = new BasicDBObject("_id", db); doc.put("partitioned", true); doc.put("primary", primaryShard); config.getCollection("databases").save(doc); // add collection record doc = new BasicDBObject("_id", ns); doc.put("lastmod", new Date()); doc.put("dropped", false); doc.put("key", shardKey); doc.put("unique", unique); config.getCollection("collections").save(doc); final DBCollection chunks = config.getCollection("chunks"); long count = chunks.count(new BasicDBObject("ns", ns)); if (count > 0) { dia = (FormDialog) getBoundUnit(Item.regenDeleteChunks); if (dia.show()) { chunks.remove(new BasicDBObject("ns", ns)); } else { return; } } // add temp collection to sort chunks with shard key final DBCollection tmpchunks = config.getCollection("_tmpchunks_" + col); tmpchunks.drop(); // should be safe environment, and dup keys should be ignored tmpchunks.setWriteConcern(WriteConcern.NORMAL); // can use shardKey as unique _id // tmpchunks.ensureIndex(shardKey, "shardKey", true); // create filter for shard fields final DBObject shardKeyFilter = new BasicDBObject(); // final DBObject shardKeyDescend = new BasicDBObject(); boolean hasId = false; for (String key : shardKey.keySet()) { shardKeyFilter.put(key, 1); if (key.equals("_id")) { hasId = true; } } if (!hasId) { shardKeyFilter.put("_id", 0); } dia = (FormDialog) getBoundUnit(Item.regenConfirm); if (!dia.show()) { return; } // now fetch all records from each shard final AtomicInteger todo = new AtomicInteger(mongoToShard.size()); for (Map.Entry<MongoClient, String> entry : mongoToShard.entrySet()) { final MongoClient mongo = entry.getKey(); final String shard = entry.getValue(); new DbJob() { @Override public Object doRun() throws Exception { BasicDBObject shardObj = (BasicDBObject) shardList.get(shard); long count = mongo.getDB(db).getCollection(col).count(); shardObj.put("count", count); DBCursor cur = mongo.getDB(db).getCollection(col).find(new BasicDBObject(), shardKeyFilter); long i = 0; int inserted = 0; long start = System.currentTimeMillis(); while (cur.hasNext() && !isCancelled()) { BasicDBObject key = (BasicDBObject) cur.next(); setProgress((int) ((++i * 100.0f) / count)); try { BasicDBObject entry = new BasicDBObject("_id", key); entry.put("_shard", shard); tmpchunks.insert(entry); ++inserted; } catch (Exception e) { getLogger().log(Level.WARNING, e.getMessage(), e); } } if (isCancelled()) { shardObj.put("cancelled", true); } shardObj.put("inserted", inserted); shardObj.put("scanTime", System.currentTimeMillis() - start); todo.decrementAndGet(); return null; } @Override public String getNS() { return tmpchunks.getFullName(); } @Override public String getShortName() { return "Scanning " + shard; } @Override public boolean isDeterminate() { return true; } }.addJob(); } new DbJob() { @Override public Object doRun() throws Exception { // wait for all shards to be done long start = System.currentTimeMillis(); while (todo.get() > 0 && !isCancelled()) { Thread.sleep(2000); } if (isCancelled()) { result.put("cancelled", true); return result; } // find highest current timestamp DBCursor cur = chunks.find().sort(new BasicDBObject("lastmod", -1)).batchSize(-1); BasicDBObject chunk = (BasicDBObject) (cur.hasNext() ? cur.next() : null); BSONTimestamp ts = (BSONTimestamp) (chunk != null ? chunk.get("lastmod") : null); // now infer chunk ranges long count = tmpchunks.count(); result.put("uniqueKeys", count); int numChunks = 0; cur = tmpchunks.find().sort(new BasicDBObject("_id", 1)); BasicDBObject prev = (BasicDBObject) cur.next(); BasicDBObject next = null; // snap prev to minkey BasicDBObject theid = (BasicDBObject) prev.get("_id"); for (String key : shardKey.keySet()) { theid.put(key, new MinKey()); } String currentShard = prev.getString("_shard"); int i = 1; while (cur.hasNext()) { next = (BasicDBObject) cur.next(); setProgress((int) ((++i * 100.0f) / count)); String newShard = next.getString("_shard"); if (newShard.equals(currentShard)) continue; // add chunk ts = getNextTimestamp(ts); chunk = getChunk(ns, shardKey, prev, next, ts); chunks.insert(chunk); prev = next; currentShard = prev.getString("_shard"); ++numChunks; } // build max next = new BasicDBObject(); for (String key : shardKey.keySet()) { next.put(key, new MaxKey()); } next = new BasicDBObject("_id", next); ts = getNextTimestamp(ts); chunk = getChunk(ns, shardKey, prev, next, ts); chunks.insert(chunk); ++numChunks; result.put("numChunks", numChunks); result.put("totalTime", System.currentTimeMillis() - start); return result; } @Override public String getNS() { return chunks.getFullName(); } @Override public String getShortName() { return "Creating Chunks"; } @Override public boolean isDeterminate() { return true; } }.addJob(); }
From source file:com.gigaspaces.persistency.MongoClientConnector.java
License:Open Source License
public void performBatch(List<BatchUnit> rows) { if (logger.isTraceEnabled()) { logger.trace("MongoClientWrapper.performBatch(" + rows + ")"); logger.trace("Batch size to be performed is " + rows.size()); }/*from ww w.j a v a 2s . c o m*/ //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); }*/ }
From source file:com.github.nlloyd.hornofmongo.adaptor.Mongo.java
License:Open Source License
@JSFunction public void remove(final String ns, Object pattern, boolean justOne) { Object rawPattern = BSONizer.convertJStoBSON(pattern, false); DBObject bsonPattern = null;/*from w w w.ja v a 2 s.co m*/ if (rawPattern instanceof DBObject) bsonPattern = (DBObject) rawPattern; com.mongodb.DB db = innerMongo.getDB(ns.substring(0, ns.indexOf('.'))); DBCollection collection = db.getCollection(ns.substring(ns.indexOf('.') + 1)); collection.setDBEncoderFactory(HornOfMongoBSONEncoder.FACTORY); try { collection.remove(bsonPattern); saveLastCalledDB(db); } catch (MongoException me) { handleMongoException(me); } }
From source file:com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.mongodb.MongoEntityPersister.java
License:Open Source License
/** * @see com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.EntityPersister * #remove(java.lang.Object)//from w ww . j a va2 s .c o m */ @Override public <T> void remove(T t) { if (t != null) { DBCollection dbcollection = getDBCollection(t.getClass(), true); String jsonObject = gson.toJson(t); DBObject dbObject = (DBObject) com.mongodb.util.JSON.parse(jsonObject.toString()); dbcollection.remove(dbObject); } }
From source file:com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.mongodb.MongoEntityPersister.java
License:Open Source License
/** * @see com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.EntityPersister * #remove(java.util.Collection)//from ww w . j a v a 2s. c o m */ @Override public <T> void remove(Collection<T> listT) { if (listT != null && listT.size() > 0) { DBCollection dbcollection; for (T t : listT) { dbcollection = getDBCollection(t.getClass(), true); String jsonObject = gson.toJson(t); DBObject dbObject = (DBObject) com.mongodb.util.JSON.parse(jsonObject.toString()); dbcollection.remove(dbObject); } } }