Example usage for com.mongodb DBCollection remove

List of usage examples for com.mongodb DBCollection remove

Introduction

In this page you can find the example usage for com.mongodb DBCollection remove.

Prototype

public WriteResult remove(final DBObject query) 

Source Link

Document

Remove documents from a collection.

Usage

From source file:org.socialhistoryservices.security.MongoTokenStore.java

License:Open Source License

public void removeAccessTokenUsingRefreshToken(String refreshToken) {

    // remove from oauth_access_token where refresh_token = ?
    final BasicDBObject query = new BasicDBObject("refresh_token", refreshToken);
    final DBCollection collection = getCollection(OAUTH_ACCESS_TOKEN);
    collection.remove(query);
}

From source file:org.springframework.data.document.mongodb.MongoTemplate.java

License:Apache License

public <T> void remove(String collectionName, final Query query, Class<T> targetClass) {
    if (query == null) {
        throw new InvalidDataAccessApiUsageException("Query passed in to remove can't be null");
    }//from   w  ww. ja va 2 s  .  c  om
    final DBObject queryObject = query.getQueryObject();
    final MongoPersistentEntity<?> entity = getPersistentEntity(targetClass);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("remove using query: " + queryObject + " in collection: " + collectionName);
    }
    execute(collectionName, new CollectionCallback<Void>() {
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            DBObject dboq = mapper.getMappedObject(queryObject, entity);
            WriteResult wr = null;
            if (writeConcern == null) {
                wr = collection.remove(dboq);
            } else {
                wr = collection.remove(dboq, writeConcern);
            }
            handleAnyWriteResultErrors(wr, dboq, "remove");
            return null;
        }
    });
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

protected <T> WriteResult doRemove(final String collectionName, final Query query, final Class<T> entityClass) {

    if (query == null) {
        throw new InvalidDataAccessApiUsageException("Query passed in to remove can't be null!");
    }/*w  w  w .ja v  a2 s.co  m*/

    Assert.hasText(collectionName, "Collection name must not be null or empty!");

    final DBObject queryObject = query.getQueryObject();
    final MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);

    return execute(collectionName, new CollectionCallback<WriteResult>() {
        public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException {

            maybeEmitEvent(new BeforeDeleteEvent<T>(queryObject, entityClass, collectionName));

            DBObject dboq = queryMapper.getMappedObject(queryObject, entity);

            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.REMOVE, collectionName,
                    entityClass, null, queryObject);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Remove using query: {} in collection: {}.",
                        new Object[] { serializeToJsonSafely(dboq), collection.getName() });
            }

            WriteResult wr = writeConcernToUse == null ? collection.remove(dboq)
                    : collection.remove(dboq, writeConcernToUse);

            handleAnyWriteResultErrors(wr, dboq, MongoActionOperation.REMOVE);

            maybeEmitEvent(new AfterDeleteEvent<T>(queryObject, entityClass, collectionName));

            return wr;
        }
    });
}

From source file:org.springframework.data.mongodb.crossstore.MongoChangeSetPersister.java

License:Apache License

public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException {
    if (cs == null) {
        log.debug("Flush: changeset was null, nothing to flush.");
        return 0L;
    }// w ww.  j av a2  s. c om

    if (log.isDebugEnabled()) {
        log.debug("Flush: changeset: {}", cs.getValues());
    }

    String collName = getCollectionNameForEntity(entity.getClass());
    if (mongoTemplate.getCollection(collName) == null) {
        mongoTemplate.createCollection(collName);
    }

    for (String key : cs.getValues().keySet()) {
        if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) {
            Object value = cs.getValues().get(key);
            final DBObject dbQuery = new BasicDBObject();
            dbQuery.put(ENTITY_ID, getPersistentId(entity, cs));
            dbQuery.put(ENTITY_CLASS, entity.getClass().getName());
            dbQuery.put(ENTITY_FIELD_NAME, key);
            DBObject dbId = mongoTemplate.execute(collName, new CollectionCallback<DBObject>() {
                public DBObject doInCollection(DBCollection collection)
                        throws MongoException, DataAccessException {
                    return collection.findOne(dbQuery);
                }
            });
            if (value == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Flush: removing: {}", dbQuery);
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {
                    public Object doInCollection(DBCollection collection)
                            throws MongoException, DataAccessException {
                        collection.remove(dbQuery);
                        return null;
                    }
                });
            } else {
                final DBObject dbDoc = new BasicDBObject();
                dbDoc.putAll(dbQuery);
                if (log.isDebugEnabled()) {
                    log.debug("Flush: saving: {}", dbQuery);
                }
                mongoTemplate.getConverter().write(value, dbDoc);
                dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName());
                if (dbId != null) {
                    dbDoc.put("_id", dbId.get("_id"));
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {
                    public Object doInCollection(DBCollection collection)
                            throws MongoException, DataAccessException {
                        collection.save(dbDoc);
                        return null;
                    }
                });
            }
        }
    }
    return 0L;
}

From source file:org.springframework.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

@Override
protected void deleteEntries(String family, final List<Object> keys) {
    mongoTemplate.execute(new DbCallback<Object>() {
        @Override/*from   w  w  w  .j  av a 2 s .  c om*/
        public Object doInDB(DB con) throws MongoException, DataAccessException {

            String collectionName = getCollectionName(getPersistentEntity());
            DBCollection dbCollection = con.getCollection(collectionName);

            MongoSession mongoSession = (MongoSession) getSession();
            MongoQuery query = mongoSession.createQuery(getPersistentEntity().getJavaClass());
            query.in(getPersistentEntity().getIdentity().getName(), keys);

            dbCollection.remove(query.getMongoQuery());

            return null;
        }
    });
}

From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java

License:Apache License

/**
 * Deletes existing registered service from mongoDB
 * //w w  w  .  jav a  2s  .co  m
 * @param serviceId
 *            Service id to be deleted
 * @param softDelete
 *            If softDelete is true, updates status instead of deleting.
 *
 * @return message string containing result
 */
public String delete(String serviceId, boolean softDelete) {
    String result = "service " + serviceId + " NOT deleted ";
    try {
        DBCollection collection = mongoClient.getDB(DATABASE_NAME).getCollection(SERVICE_COLLECTION_NAME);

        if (softDelete) {
            JacksonDBCollection<Service, String> coll = JacksonDBCollection.wrap(collection, Service.class,
                    String.class);
            Query query = DBQuery.is("serviceId", serviceId);
            WriteResult<Service, String> writeResult = coll.update(query, DBUpdate
                    .set("resourceMetadata.availability", ResourceMetadata.STATUS_TYPE.OFFLINE.toString()));
            int recordsChanged = writeResult.getN();

            // Return the id that was used
            if (recordsChanged == 1) {
                result = " service " + serviceId + " deleted ";
            }
        } else {
            // Delete the existing entry for the Job
            BasicDBObject deleteQuery = new BasicDBObject();
            deleteQuery.append("serviceId", serviceId);
            collection.remove(deleteQuery);
            result = " service " + serviceId + " deleted ";
            // If any Service Queue exists, also delete that here.
            deleteServiceQueue(serviceId);
        }

        logger.log(String.format("Deleting resource from MongoDB %s", serviceId), Severity.INFORMATIONAL,
                new AuditElement("serviceController", "Deleted Service", serviceId));

        return result;
    } catch (MongoException ex) {
        String message = String.format("Error Deleting Mongo Service entry : %s", ex.getMessage());
        logger.log(message, Severity.ERROR);
        LOGGER.error(message, ex);
    }

    return result;
}

From source file:org.vertx.java.busmods.persistor.MongoPersistor.java

License:Apache License

private void doDelete(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;/*from  w  w w.j av a  2  s. co  m*/
    }
    JsonObject matcher = getMandatoryObject("matcher", message);
    if (matcher == null) {
        return;
    }
    DBCollection coll = db.getCollection(collection);
    DBObject obj = jsonToDBObject(matcher);
    WriteResult res = coll.remove(obj);
    int deleted = res.getN();
    JsonObject reply = new JsonObject().putNumber("number", deleted);
    sendOK(message, reply);
}

From source file:org.wrml.contrib.runtime.service.mongo.MongoService.java

License:Apache License

@Override
public void delete(final Keys keys, final Dimensions dimensions) {

    final DBObject mongoKeys = createMongoKeys(keys);

    for (final URI schemaUri : keys.getKeyedSchemaUris()) {

        final String collectionName = convertToCollectionName(schemaUri);
        if (!_Mongo.collectionExists(collectionName)) {
            continue;
        }//from   w ww  .jav a2  s .  co m

        final DBCollection mongoCollection = _Mongo.getCollection(collectionName);
        if (mongoCollection == null) {
            continue;
        }

        final DBObject mongoObject = mongoCollection.findOne(mongoKeys);

        if (mongoObject != null) {
            final WriteResult mongoWriteResult = mongoCollection.remove(mongoObject);

            final String errorMessage = mongoWriteResult.getError();
            if (errorMessage != null) {
                LOG.error(getConfiguration().getName() + " - Error deleting model (" + errorMessage
                        + "). Keys:\n" + keys);
            }
        }
    }
}

From source file:payroll.FrmAdmin.java

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    Connect1 j = new Connect1();
    DBCollection dbc = j.connect("Emp_Records");

    BasicDBObject bdb = new BasicDBObject();
    BasicDBObject bdb1 = new BasicDBObject();
    bdb.put("ID", txtid.getText());
    DBCursor cursor = dbc.find(bdb);/*from   www .  j  av a2 s. co m*/
    if (cursor.hasNext()) {
        dbc.remove(bdb);
        final JPanel p2 = new JPanel();

        txtid.setText("");
    } else {
        final JPanel p2 = new JPanel();
        JOptionPane.showMessageDialog(p2, "Employee Not Found", "Failure", JOptionPane.ERROR_MESSAGE);
        txtid.setText("");
        return;
    }
    DBCollection dbc1 = j.connect("Passwords");
    bdb1.put("Employee Id", txtid.getText());
    cursor = dbc1.find(bdb1);
    if (cursor.hasNext()) {
        dbc.remove(bdb);
        final JPanel p2 = new JPanel();
        JOptionPane.showMessageDialog(p2, "Employee Record Deleted", "Deleted",
                JOptionPane.INFORMATION_MESSAGE);
        txtid.setText("");
    } else {
        final JPanel p2 = new JPanel();
        JOptionPane.showMessageDialog(p2, "Employee Not Found", "Failure", JOptionPane.ERROR_MESSAGE);
        txtid.setText("");
    }

}

From source file:poke.server.storage.jdbc.DatabaseStorage.java

License:Apache License

@Override
public boolean deleteImage(Request request) {
    // TODO Auto-generated method stub
    // Routing.Builder 
    try {// www  . j a  v  a 2s .  c o m
        DBCollection dbColl = db.getCollection("ImageRepository");
        BasicDBObject ref = new BasicDBObject();
        ref.put("uuid", request.getBody().getPhotoPayload().getUuid());
        DBCursor dbc = dbColl.find(ref);
        try {
            if (dbc.hasNext()) {
                dbColl.remove(ref);
                logger.debug("Deleted" + dbc.next());
                return true;
            } else {
                // Set forward node as leader of next cluster.
                //hdb.setToNode(value);
            }
        } finally {
            dbc.close();
        }
    } catch (Exception e) {
        logger.debug(e.getClass().getName() + ": " + e.getMessage());
    }
    return false;
}