List of usage examples for com.mongodb DBCollection findAndRemove
@Nullable public DBObject findAndRemove(@Nullable final DBObject query)
From source file:DeleteUser.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.setHeader("Access-Control-Allow-Origin", "*"); try {//from w ww . ja v a 2 s. c o m out = response.getWriter(); String id = request.getParameter("id"); System.out.println("id received : " + id); MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases DB db = mongoClient.getDB("XHiring"); System.out.println("Connect to database successfully"); DBCollection coll = db.getCollection("users"); System.out.println("Collection users selected successfully"); //read example try { BasicDBObject query = new BasicDBObject("_id", new ObjectId(id)); coll.findAndRemove(query); success = new JSONObject(); success.put("message", "document deleted"); out.println(success); } catch (NullPointerException ex) { error = new JSONObject(); error.put("message", "No result found"); out.println(error); } System.out.println("Document deleted successfully"); } catch (Exception e) { exception = new JSONObject(); try { exception.put("message", "exception"); out.println(exception); } catch (JSONException ex) { Logger.getLogger(DeleteUser.class.getName()).log(Level.SEVERE, null, ex); } System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } }
From source file:com.continuent.tungsten.replicator.applier.MongoApplier.java
License:Open Source License
/** * Applies row updates to MongoDB. Statements are discarded. {@inheritDoc} * /*from w w w. j ava 2s .c om*/ * @see com.continuent.tungsten.replicator.applier.RawApplier#apply(com.continuent.tungsten.replicator.event.DBMSEvent, * com.continuent.tungsten.replicator.event.ReplDBMSHeader, boolean, * boolean) */ @Override public void apply(DBMSEvent event, ReplDBMSHeader header, boolean doCommit, boolean doRollback) throws ReplicatorException, ConsistencyException, InterruptedException { ArrayList<DBMSData> dbmsDataValues = event.getData(); // Iterate through values inferring the database name. for (DBMSData dbmsData : dbmsDataValues) { if (dbmsData instanceof StatementData) { if (logger.isDebugEnabled()) logger.debug("Ignoring statement"); } else if (dbmsData instanceof RowChangeData) { RowChangeData rd = (RowChangeData) dbmsData; for (OneRowChange orc : rd.getRowChanges()) { // Get the action as well as the schema & table name. ActionType action = orc.getAction(); String schema = orc.getSchemaName(); String table = orc.getTableName(); if (logger.isDebugEnabled()) { logger.debug("Processing row update: action=" + action + " schema=" + schema + " table=" + table); } // Process the action. if (action.equals(ActionType.INSERT)) { // Connect to the schema and collection. DB db = m.getDB(schema); DBCollection coll = db.getCollection(table); // Fetch column names. List<ColumnSpec> colSpecs = orc.getColumnSpec(); // Make a document and insert for each row. Iterator<ArrayList<ColumnVal>> colValues = orc.getColumnValues().iterator(); while (colValues.hasNext()) { BasicDBObject doc = new BasicDBObject(); ArrayList<ColumnVal> row = colValues.next(); for (int i = 0; i < row.size(); i++) { Object value = row.get(i).getValue(); setValue(doc, colSpecs.get(i), value); } if (logger.isDebugEnabled()) logger.debug("Adding document: doc=" + doc.toString()); coll.insert(doc); } } else if (action.equals(ActionType.UPDATE)) { // Connect to the schema and collection. DB db = m.getDB(schema); DBCollection coll = db.getCollection(table); // Ensure required indexes are present. ensureIndexes(coll, orc); // Fetch key and column names. List<ColumnSpec> keySpecs = orc.getKeySpec(); List<ColumnSpec> colSpecs = orc.getColumnSpec(); ArrayList<ArrayList<OneRowChange.ColumnVal>> keyValues = orc.getKeyValues(); ArrayList<ArrayList<OneRowChange.ColumnVal>> columnValues = orc.getColumnValues(); // Iterate across the rows. for (int row = 0; row < columnValues.size() || row < keyValues.size(); row++) { List<ColumnVal> keyValuesOfRow = keyValues.get(row); List<ColumnVal> colValuesOfRow = columnValues.get(row); // Prepare key values query to search for rows. DBObject query = new BasicDBObject(); for (int i = 0; i < keyValuesOfRow.size(); i++) { setValue(query, keySpecs.get(i), keyValuesOfRow.get(i).getValue()); } BasicDBObject doc = new BasicDBObject(); for (int i = 0; i < colValuesOfRow.size(); i++) { setValue(doc, colSpecs.get(i), colValuesOfRow.get(i).getValue()); } if (logger.isDebugEnabled()) { logger.debug("Updating document: query=" + query + " doc=" + doc); } DBObject updatedRow = coll.findAndModify(query, doc); if (logger.isDebugEnabled()) { if (updatedRow == null) logger.debug("Unable to find document for update: query=" + query); else logger.debug("Documented updated: doc=" + doc); } } } else if (action.equals(ActionType.DELETE)) { // Connect to the schema and collection. DB db = m.getDB(schema); DBCollection coll = db.getCollection(table); // Ensure required indexes are present. ensureIndexes(coll, orc); List<ColumnSpec> keySpecs = orc.getKeySpec(); ArrayList<ArrayList<OneRowChange.ColumnVal>> keyValues = orc.getKeyValues(); ArrayList<ArrayList<OneRowChange.ColumnVal>> columnValues = orc.getColumnValues(); // Iterate across the rows. for (int row = 0; row < columnValues.size() || row < keyValues.size(); row++) { List<ColumnVal> keyValuesOfRow = keyValues.get(row); // Prepare key values query to search for rows. DBObject query = new BasicDBObject(); for (int i = 0; i < keyValuesOfRow.size(); i++) { setValue(query, keySpecs.get(i), keyValuesOfRow.get(i).getValue()); } if (logger.isDebugEnabled()) { logger.debug("Deleting document: query=" + query); } DBObject deletedRow = coll.findAndRemove(query); if (logger.isDebugEnabled()) { if (deletedRow == null) logger.debug("Unable to find document for delete"); else logger.debug("Documented deleted: doc=" + deletedRow); } } } else { logger.warn("Unrecognized action type: " + action); return; } } } else if (dbmsData instanceof LoadDataFileFragment) { if (logger.isDebugEnabled()) logger.debug("Ignoring load data file fragment"); } else if (dbmsData instanceof RowIdData) { if (logger.isDebugEnabled()) logger.debug("Ignoring row ID data"); } else { logger.warn("Unsupported DbmsData class: " + dbmsData.getClass().getName()); } } // Mark the current header and commit position if requested. this.latestHeader = header; if (doCommit) commit(); }
From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java
License:Apache License
/** * Prints all the rows of data returned by the API. * @param gaData the data returned from the API. * @param collection//from ww w .j a v a 2s.co m * @param d */ private static void insertVisitedCompaniesData(GaData gaData, DBCollection collection, Date d) throws JSONException { if (gaData.getTotalResults() > 0) { System.out.println("Data Table: " + collection); for (List<String> rowValues : gaData.getRows()) { Map jsonMap = (Map) JSON.parse(rowValues.get(0)); if (jsonMap.get("demandbase_sid") == null) { continue; } DBObject dbObject = new BasicDBObject(jsonMap); dbObject.removeField("ip"); HashMap<Object, Object> map = new HashMap<Object, Object>(); map.put("demandbase_sid", dbObject.get("demandbase_sid")); BasicDBObject objectToRemove = new BasicDBObject(map); DBObject andRemove = collection.findAndRemove(objectToRemove); if (andRemove == null) { dbObject.put("firstVisitDate", new SimpleDateFormat("yyyy/MM/dd").format(d)); } else { dbObject.put("firstVisitDate", andRemove.get("firstVisitDate")); } collection.insert(dbObject); } } else { System.out.println("No data"); } }
From source file:com.ijuru.ijambo.dao.PlayerDAO.java
License:Open Source License
/** * Removes a player/*from w w w.j a va 2s. c om*/ * @param player the player */ public void remove(Player player) { DBCollection players = db.getCollection("players"); BasicDBObject query = new BasicDBObject(); query.put("identifier", player.getIdentifier()); players.findAndRemove(query); }
From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java
License:Apache License
/** * @see org.apache.sling.api.resource.ModifyingResourceProvider#commit(ResourceResolver) *//*w w w . ja v a 2 s .c o m*/ public void commit(final ResourceResolver resolver) throws PersistenceException { try { for (final String deleted : this.deletedResources) { final String[] info = this.extractResourceInfo(deleted); // check if the collection still exists final DBCollection col = this.getCollection(info[0]); if (col != null) { if (col.findAndRemove(QueryBuilder.start(getPROP_PATH()).is(info[1]).get()) != null) { this.context.notifyRemoved(info); } } } for (final MongoDBResource changed : this.changedResources.values()) { final DBCollection col = this.context.getDatabase().getCollection(changed.getCollection()); if (col != null) { final String[] info = new String[] { changed.getCollection(), changed.getProperties().get(getPROP_PATH()).toString() }; // create or update? if (changed.getProperties().get(PROP_ID) != null) { col.update(QueryBuilder.start(getPROP_PATH()) .is(changed.getProperties().get(getPROP_PATH())).get(), changed.getProperties()); this.context.notifyUpdated(info); } else { // create col.save(changed.getProperties()); this.context.notifyUpdated(info); } } else { throw new PersistenceException("Unable to create collection " + changed.getCollection(), null, changed.getPath(), null); } } } finally { this.revert(resolver); } }
From source file:org.eclipselabs.mongoemf.handlers.MongoURIHandlerImpl.java
License:Open Source License
@Override public void delete(URI uri, Map<?, ?> options) throws IOException { // It is assumed that delete is called with the URI path /database/collection/id DBCollection collection = getCollection(uri, options); collection.findAndRemove(new BasicDBObject(Keywords.ID_KEY, MongoUtils.getID(uri))); }
From source file:org.exist.mongodb.xquery.mongodb.collection.FindAndRemove.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {/* w w w . ja v a2 s. c o m*/ // Verify clientid and get client String mongodbClientId = args[0].itemAt(0).getStringValue(); MongodbClientStore.getInstance().validate(mongodbClientId); MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId); // Get parameters String dbname = args[1].itemAt(0).getStringValue(); String collection = args[2].itemAt(0).getStringValue(); BasicDBObject query = (args.length >= 4) ? (BasicDBObject) JSON.parse(args[3].itemAt(0).getStringValue()) : null; // Get collection in database DB db = client.getDB(dbname); DBCollection dbcol = db.getCollection(collection); // Execute query DBObject result = dbcol.findAndRemove(query); // Parse results Sequence retVal = (result == null) ? Sequence.EMPTY_SEQUENCE : new StringValue(result.toString()); return retVal; } catch (JSONParseException ex) { LOG.error(ex.getMessage()); throw new XPathException(this, MongodbModule.MONG0004, ex.getMessage()); } catch (XPathException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, ex.getMessage(), ex); } catch (MongoException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage()); } catch (Throwable ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0003, ex.getMessage()); } }
From source file:org.hibernate.ogm.datastore.mongodb.MongoDBDialect.java
License:LGPL
@Override public boolean removeTupleWithOptimisticLock(EntityKey entityKey, Tuple oldLockState, TupleContext tupleContext) {// w w w. j a va 2s . c om DBObject toDelete = prepareIdObject(entityKey); for (String versionColumn : oldLockState.getColumnNames()) { toDelete.put(versionColumn, oldLockState.get(versionColumn)); } DBCollection collection = getCollection(entityKey); DBObject deleted = collection.findAndRemove(toDelete); return deleted != null; }
From source file:rapture.sheet.mongodb.MongoCellStore.java
License:Open Source License
public void deleteColumn(final String sheetName, final int column) { final DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName); MongoRetryWrapper<Object> wrapper = new MongoRetryWrapper<Object>() { public DBCursor makeCursor() { // Deleting a column is two things. // (a) find and remove all cells (in all dimensions) that have // this as a // column // (b) modify all cells that have a column > this column, // decreasing // their column by 1 BasicDBObject query = new BasicDBObject(); query.put(KEY, sheetName);/*from www .j a v a 2 s.c o m*/ query.put(COL, column); collection.findAndRemove(query); BasicDBObject changeQuery = new BasicDBObject(); changeQuery.put(KEY, sheetName); BasicDBObject testQuery = new BasicDBObject(); testQuery.put("$gt", column); changeQuery.put(COL, testQuery); return collection.find(changeQuery); } public Object action(DBCursor cursor) { while (cursor.hasNext()) { BasicDBObject object = (BasicDBObject) cursor.next(); object.put(COL, object.getInt(COL) - 1); object.put(EPOCH, getLatestEpoch(sheetName, object.getInt(DIM))); collection.save(object); } return null; } }; @SuppressWarnings("unused") Object o = wrapper.doAction(); }
From source file:rapture.sheet.mongodb.MongoCellStore.java
License:Open Source License
public void deleteRow(final String sheetName, final int row) { final DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName); MongoRetryWrapper<Object> wrapper = new MongoRetryWrapper<Object>() { public DBCursor makeCursor() { // Deleting a column is two things. // (a) find and remove all cells (in all dimensions) that have // this as a // column // (b) modify all cells that have a column > this column, // decreasing // their column by 1 DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName); BasicDBObject query = new BasicDBObject(); query.put(KEY, sheetName);//w w w.j a v a2 s.c om query.put(ROW, row); collection.findAndRemove(query); BasicDBObject changeQuery = new BasicDBObject(); changeQuery.put(KEY, sheetName); BasicDBObject testQuery = new BasicDBObject(); testQuery.put("$gt", row); changeQuery.put(ROW, testQuery); return collection.find(changeQuery); } public Object action(DBCursor cursor) { while (cursor.hasNext()) { BasicDBObject object = (BasicDBObject) cursor.next(); object.put(ROW, object.getInt(ROW) - 1); object.put(EPOCH, getLatestEpoch(sheetName, object.getInt(DIM))); collection.save(object); } return null; } }; @SuppressWarnings("unused") Object o = wrapper.doAction(); }