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.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@DELETE
@Path("/databases/{dbName}/collections/{collName}/documents/{docId}")
@Override/*from  www . j  a  v a  2  s.co  m*/
public Response deleteDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @PathParam("docId") String docId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
        @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                if (!StringUtils.isNullOrEmpty(docId)) {
                    DBObject query = new BasicDBObject();
                    query.put("_id", new ObjectId(docId));
                    dbCollection.remove(query);
                    response = Response.ok().build();
                }
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "deleteDocument");
    }
    return response;
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@DELETE
@Path("/databases/{dbName}/collections/{collName}/documents")
@Override/*from  w  w w .  jav  a 2  s.c  om*/
public Response deleteDocuments(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                DBCursor cursor = dbCollection.find();
                while (cursor.hasNext()) {
                    DBObject found = cursor.next();
                    if (found != null) {
                        dbCollection.remove(found);
                    }
                }
                response = Response.ok().build();
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "deleteDocuments");
    }
    return response;
}

From source file:org.fastmongo.odm.bson.repository.BsonMongoTemplate.java

License:Apache License

/**
 * Removes all document from the given collection satisfying the given Query.
 *
 * @param clazz the collection class.//from w  w w.ja va 2s .co m
 * @param query specifies the selection criteria (<tt>nullable</tt>).
 */
public void remove(Class<?> clazz, Query query) {
    DBCollection collection = getCollection(clazz);
    collection.remove(query != null ? query.toDbObject() : null);
}

From source file:org.fiware.apps.repository.dao.impl.MongoCollectionDAO.java

License:BSD License

@Override
public Boolean deleteCollection(String id) throws DatasourceException {

    db.requestStart();//  w  ww.ja  v  a2  s  . c o m

    try {
        //delete Resources
        DBCollection mongoResource = db.getCollection(MongoResourceDAO.MONGO_COLL_NAME);
        BasicDBObject query = new BasicDBObject();
        Pattern p = Pattern.compile("^" + id + "/[a-zA-Z0-9_\\.\\-\\+]*");
        query.put("id", p);
        List<DBObject> objs = mongoResource.find(query).toArray();

        for (DBObject obj : objs) {
            virtuosoResourceDAO.deleteResource(obj.get("id").toString());
            mongoResource.remove(obj);
        }

        //delete Collections
        BasicDBObject queryC = new BasicDBObject();
        Pattern pC = Pattern.compile("^" + id + "/[a-zA-Z0-9_\\.\\-\\+]*");
        queryC.put("id", pC);
        List<DBObject> objsC = mongoCollection.find(queryC).toArray();

        for (DBObject obj : objsC) {
            mongoCollection.remove(obj);
        }
    } catch (Exception e) {
        db.requestDone();
        throw new DatasourceException(e.getMessage(), ResourceCollection.class);
    }

    db.requestDone();

    try {
        db.requestStart();
        Pattern pat = Pattern.compile(id);
        BasicDBObject query = new BasicDBObject("id", pat);
        DBObject obj = mongoCollection.findOne(query);
        if (obj == null) {
            db.requestDone();
            return false;
        }
        mongoCollection.remove(obj);
        db.requestDone();
        return true;

    } catch (IllegalArgumentException e) {
        db.requestDone();
        throw new DatasourceException("Error deleting Collection with ID " + id + " " + e.getMessage(),
                ResourceCollection.class);
    }
}

From source file:org.forgerock.openidm.repo.mongodb.impl.MongoDBRepoService.java

License:Open Source License

/**
 * Deletes the specified object from the object set.
 *
 * @param fullId the identifier of the object to be deleted.
 * @param rev the version of the object to delete or {@code null} if not provided.
 * @throws NotFoundException if the specified object could not be found. 
 * @throws ForbiddenException if access to the object is forbidden.
 * @throws ConflictException if version is required but is {@code null}.
 * @throws PreconditionFailedException if version did not match the existing object in the set.
 *///from   w  w  w  .j  a va  2s. c  om
@Override
public void delete(String fullId, String rev) throws ObjectSetException {
    String localId = getLocalId(fullId);
    String type = getObjectType(fullId, false);

    if (rev == null) {
        throw new ConflictException("Object passed into delete does not have revision it expects set.");
    }

    int ver = Integer.valueOf(DocumentUtil.parseVersion(rev)); // This throws ConflictException if parse fails

    DBCollection collection = getCollection(type);
    DBObject existingDoc = predefinedQueries.getByID(localId, collection);
    if (existingDoc == null) {
        throw new NotFoundException("Object does not exist for delete on: " + fullId);
    }

    WriteResult res = collection.remove(new BasicDBObject(DocumentUtil.TAG_ID, localId));
}

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

License:Apache License

@Override
protected void deleteEntries(String family, final List<Object> keys) {
    mongoTemplate.execute(new DbCallback<Object>() {
        public Object doInDB(DB con) throws MongoException, DataAccessException {
            @SuppressWarnings("hiding")
            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;
        }// ww w.java  2  s. com
    });
}

From source file:org.greenmongoquery.db.service.impl.MongoServiceImpl.java

License:Open Source License

public String deleteDocument(String json, String dbname, String collectionName, Mongo mongo, String id) {

    String result = null;//from  w ww  .  j  ava 2s. c o  m
    DB db = mongo.getDB(dbname);
    DBObject orgDbObject = new BasicDBObject("_id", new ObjectId(id));
    logger.info("id " + id);
    logger.info("k object " + orgDbObject.toString());

    DBCollection coll = db.getCollection(collectionName);
    DBObject found = coll.findOne(orgDbObject);
    coll.remove(found);
    result = "delete document : _id=  " + id;
    return result;

}

From source file:org.hibernate.ogm.dialect.mongodb.MongoDBDialect.java

License:Open Source License

@Override
public void removeTuple(EntityKey key) {
    DBCollection collection = this.getCollection(key);
    DBObject toDelete = this.getObject(key);
    if (toDelete != null) {
        collection.remove(toDelete);
    } else {/*from w w w.  j  a va 2  s.co  m*/
        if (log.isDebugEnabled()) {
            log.debugf("Unable to remove %1$s (object not found)", key.getColumnValues()[0]);
        }
    }
}

From source file:org.hibernate.ogm.dialect.mongodb.MongoDBDialect.java

License:Open Source License

@Override
public void removeAssociation(AssociationKey key) {
    DBCollection collection = getAssociationCollection(key);
    DBObject query = MongoHelpers.associationKeyToObject(key);

    int nAffected = collection.remove(query).getN();
    log.removedAssociation(nAffected);/*www  . jav a 2 s  .  c  o m*/
}

From source file:org.i3xx.step.clockmongo.service.impl.ClockPersistenceServiceImpl.java

License:Apache License

/**
 * @param nspc The namespace/*from  www.  j a  v  a 2s.co  m*/
 * @param symbol The symbol to remove
 */
public void removeMapping(String nspc, String symbol) {
    logger.trace("Removes the object nspc:{}, symbol:{}", nspc, symbol);

    DBCollection col = ensureCollection(nspc, symbol);
    col.remove(symbolQuery(symbol));
}