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:com.tomtom.speedtools.mongodb.DaoUtils.java

License:Apache License

/**
 * Removes the given object from the given collection.
 *
 * @param <T>        Element type.
 * @param collection Collection from which to remove the object.
 * @param field      The field to match.
 * @param value      The value of the field.
 * @throws EntityRemoveException Thrown if the object cannot be removed. The error will have been logged.
 *///from  w ww.  jav  a 2  s  . c om
public static <T> void removeEntityByField(@Nonnull final DBCollection collection,
        @Nonnull final EntityMapper<?>.Field<T> field, @Nonnull final T value) throws EntityRemoveException {
    assert collection != null;
    assert field != null;
    assert value != null;

    try {
        final MongoDBQuery dbQuery = new MongoDBQuery().eq(field, value);
        collection.remove(dbQuery.toDBObject());
    } catch (final MapperException | MongoException e) {
        final String message = "Remove entity failed: field=" + field.getFieldName() + ", collection="
                + collection.getName() + '.';
        LOG.error("removeEntityByField: " + message, e);
        throw new EntityRemoveException(message, e);
    }
}

From source file:com.ultratechnica.mongodb.Main.java

License:Apache License

public static void main(String[] args) {

    log.info("=============================================================================================\n"
            + "                       _   _     _                 \n"
            + " |\\/|  _  ._   _   _  | \\ |_)   |_)  _  ._   _ |_  \n"
            + " |  | (_) | | (_| (_) |_/ |_)   |_) (/_ | | (_ | | \n"
            + "               _|                                  \n"
            + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n"
            + "Licensed to Apache "
            + "=============================================================================================\n");
    Options options = getOptions();/*from  w w  w.j  av  a 2s  . c  om*/

    CommandLine commandLine = parseArgs(args, options);

    MongoClient client = null;

    if (commandLine.hasOption("host") && commandLine.hasOption("port")) {

        String host = commandLine.getOptionValue("host");
        String port = commandLine.getOptionValue("port");

        try {

            client = new MongoClient(host, Integer.parseInt(port));
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on port [{}]", host, port);
        }
    } else if (options.hasOption("host")) {

        String host = commandLine.getOptionValue("host");

        try {
            client = new MongoClient(host);
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on default port ()", host);
        }
    } else {

        try {
            client = new MongoClient();
        } catch (UnknownHostException e) {
            log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT);
        }
    }

    if (client == null) {
        System.out.println("Exiting, due to previous connection errors");
        System.exit(1);
    }

    ServerAddress clientAddress = client.getAddress();
    log.info("Connected to MongoDB [{}]", clientAddress);

    MongoClientOptions mongoClientOptions = client.getMongoClientOptions();

    log.info("=============================================================================================\n"
            + "Using Mongo Client options:\n" + "\tConnections per host: "
            + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: "
            + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: "
            + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: "
            + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: "
            + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n"
            + "\tMax threads allowed to block for conneciton multipler: "
            + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: "
            + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: "
            + mongoClientOptions.getReadPreference() + "\n"
            + "=============================================================================================\n");

    String items = commandLine.getOptionValue("n");

    int numberOfItems = 0;
    try {
        numberOfItems = Integer.parseInt(items);
    } catch (NumberFormatException e) {
        log.error("The parameter provided for -n was not an integer [{}]", items);
        System.exit(1);
    }

    DB local = client.getDB("local");

    DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME);

    log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems,
            DEFAULT_COLLECTION_NAME);

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < numberOfItems; i++) {

        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date())
                .add("field1", "123456").add("field2", "2345678")
                .add("field3", "123123231313131232131231231231123132123123123").add("field4", true);

        WriteResult result = collection.insert(builder.get());
        if (!result.getLastError().ok()) {
            log.error("An error occurred [{}]", result.getLastError());
        }
    }

    long endTime = System.currentTimeMillis();

    log.info("Finished benchmarking.");
    long timeTakenMillis = endTime - startTime;

    float timeTaken = (float) timeTakenMillis / 1000;

    log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n"
            + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n"
            + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n");

    log.info("Removing test data...");
    collection.remove(new BasicDBObject());
    log.info("Cleared collection [test]");
}

From source file:com.uquetignyadminapp.connection.ConnectionMongoDB.java

public void supprimerTable(String table) {
    DBCollection col = getRecordsOfSpecificCollection(table);
    DBCursor cursor = col.find();//from   w w w .j a  v  a  2s . co m
    while (cursor.hasNext()) {
        col.remove(cursor.next());
    }
    col.drop();

}

From source file:com.xemsdoom.xeco.core.storage.mongodb.MongoDBStorage.java

License:Open Source License

@Override
public boolean saveAccounts(Set<Account> accounts, Set<String> deleted) {

    Tracker.log("Attempting to save Accounts in MongoDB...");
    long start = System.currentTimeMillis();

    DBCollection coll = db.getCollection(collection);

    // Remove deleted accounts from collection
    for (String acc : deleted) {
        coll.remove(new BasicDBObject("_id", acc));
    }//from   w ww.  j  a  v a 2s.  c  o  m

    // Update, Insert
    for (Account acc : accounts) {

        BasicDBObject query = new BasicDBObject("_id", acc.getAccountName());
        DBCursor cursor = coll.find(query);

        // Check if document already exists
        if (cursor.hasNext()) {

            DBObject old = cursor.next();
            BasicDBObject update = new BasicDBObject();

            // Update
            update.put("_id", acc.getAccountName());
            update.put("balance", acc.getBalance());
            update.put("freezed", acc.isFrozen());
            coll.update(old, update);

        } else {

            // Insert
            BasicDBObject insert = new BasicDBObject("_id", acc.getAccountName())
                    .append("balance", acc.getBalance()).append("freezed", acc.isFrozen());
            coll.insert(insert);
        }
    }

    Tracker.log("Saving Accounts in MongoDB took: "
            .concat(String.valueOf((System.currentTimeMillis() - start)).concat("ms.")));
    Tracker.log("Saved " + accounts.size() + " and deleted " + deleted.size() + " Accounts.");
    return true;
}

From source file:de.fhg.igd.mongomvcc.impl.MongoDBVMaintenance.java

License:Open Source License

@Override
public long pruneDanglingCommits(long expiry, TimeUnit unit) {
    long[] cids = findDanglingCommits(expiry, unit);
    DBCollection collCommits = _db.getDB().getCollection(MongoDBConstants.COLLECTION_COMMITS);

    //delete commits in chunks, so we avoid sending an array that is
    //larger than the maximum document size
    final int sliceCount = 1000;
    for (int i = 0; i < cids.length; i += sliceCount) {
        int maxSliceCount = Math.min(sliceCount, cids.length - i);
        long[] slice = new long[maxSliceCount];
        System.arraycopy(cids, i, slice, 0, maxSliceCount);
        collCommits.remove(new BasicDBObject(MongoDBConstants.ID, new BasicDBObject("$in", slice)));
    }/*from  w ww  .j a  v  a 2s  .  c o m*/

    return cids.length;
}

From source file:de.fhg.igd.mongomvcc.impl.MongoDBVMaintenance.java

License:Open Source License

@Override
public long pruneUnreferencedDocuments(String collection, long expiry, TimeUnit unit) {
    long[] oids = findUnreferencedDocuments(collection, expiry, unit);
    DBCollection coll = _db.getDB().getCollection(collection);

    //delete documents in chunks, so we avoid sending an array that is
    //larger than the maximum document size
    final int sliceCount = 1000;
    for (int i = 0; i < oids.length; i += sliceCount) {
        int maxSliceCount = Math.min(sliceCount, oids.length - i);
        long[] slice = new long[maxSliceCount];
        System.arraycopy(oids, i, slice, 0, maxSliceCount);
        coll.remove(new BasicDBObject(MongoDBConstants.ID, new BasicDBObject("$in", slice)));
    }/*from w w  w  . j  av  a  2  s  .c o m*/

    return oids.length;
}

From source file:de.flapdoodle.mongoom.datastore.Datastore.java

License:Apache License

private <T> void store(Operation operation, T entity) {
    IEntityTransformation<T> converter = _transformations.transformation((Class<T>) entity.getClass());
    DBCollection dbCollection = _db.getCollection(converter.collection().name());
    Object idValue = converter.getId(entity);
    Object versionValue = converter.getVersion(entity);

    //      if (idValue == null)
    //         throw new MappingException(entity.getClass(), "Key is NULL");
    //      DBObject convertedEntity = converter.convertTo(entity);

    BasicDBObject key = new BasicDBObject();
    key.put(Const.ID_FIELDNAME, idValue);
    if (versionValue != null)
        key.put(Const.VERSION_FIELDNAME, versionValue);

    boolean reReadId = true;
    boolean mustHaveObjectId = false;
    boolean update = false;

    switch (operation) {
    case Delete://from  w ww.j a va 2 s . c om
        mustHaveObjectId = true;
        reReadId = false;
        break;
    case Save:
        mustHaveObjectId = true;
        break;
    case Update:
        reReadId = false;
        update = true;
        if (idValue == null)
            throw new MappingException(entity.getClass(), "Can not update Entities with Id not set");
        break;
    }

    try {
        _db.requestStart();
        if (mustHaveObjectId) {
            if ((idValue != null) && (!(idValue instanceof ObjectId))) {
                throw new MappingException(entity.getClass(), "Can not save Entities with custom Id");
            }
        }

        converter.newVersion(entity);
        DBObject convertedEntity = converter.asObject(entity);

        switch (operation) {
        case Insert:
            _logger.fine("Insert: " + convertedEntity);
            if (idValue != null) {
                _logger.log(Level.WARNING, "Insert with Id set: " + idValue, new Exception());
            }
            dbCollection.insert(convertedEntity);
            break;
        case Update:
            _logger.fine("Update: " + convertedEntity + " (Id: " + idValue + ")");
            //               BasicDBObject updateQuery=new BasicDBObject();
            //               updateQuery.put(Const.ID_FIELDNAME, idValue);
            dbCollection.update(key, convertedEntity, false, false);
            break;
        case Save:
            _logger.fine("Save: " + convertedEntity);
            dbCollection.save(convertedEntity);
            break;
        case Delete:
            _logger.fine("Delete: " + key);
            dbCollection.remove(key);
            break;
        default:
            throw new ObjectMapperException("Operation not supported: " + operation);
        }

        if (reReadId) {
            Object savedIdValue = convertedEntity.get(Const.ID_FIELDNAME);
            converter.setId(entity, savedIdValue);
        }

        Errors.checkError(_db, operation);

        if (operation == Operation.Delete) {
            converter.setId(entity, null);
        }
    } finally {
        _db.requestDone();
    }

}

From source file:edu.stanford.epad.common.util.MongoDBOperations.java

License:Open Source License

/**
 * Deletes json annotation from mongoDB/*from w  w w.  j  a v a  2  s.c om*/
 * 
 * @param annotationID
 * @param collection
 * @throws Exception
 */
public static void deleteAnotationInMongo(String annotationID, String collection) throws Exception {
    try {
        DB db = MongoDBOperations.getMongoDB();
        if (db == null) {
            log.warning("No connection to Mongo DB");
            return;
        }
        DBCollection dbColl = db.getCollection(collection);
        BasicDBObject query = new BasicDBObject();
        query.put("ImageAnnotationCollection.uniqueIdentifier.root", annotationID);
        DBCursor cursor = dbColl.find(query);
        if (cursor.count() > 0) {
            log.info("Deleting annotation in mongoDB:" + annotationID + " in " + collection);
            DBObject annotation = cursor.next();
            dbColl.remove(annotation);
        } else {
            log.info("Annotation not found in mongoDB:" + annotationID + " in " + collection);
        }
    } catch (Exception e) {
        log.warning("Error deleting AIM from mongodb:", e);
        throw e;
    }
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

@Override
public void removeEntireRecord(String collectionName, String guid) throws FailedDBOperationException {
    String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName();
    try {/*from w w  w.ja  va 2 s . c o m*/
        DBCollection collection = db.getCollection(collectionName);
        BasicDBObject query = new BasicDBObject(primaryKey, guid);
        collection.remove(query);
    } catch (MongoException e) {
        DatabaseConfig.getLogger().log(Level.FINE, "{0} removeEntireRecord failed: {1}",
                new Object[] { dbName, e.getMessage() });
        throw new FailedDBOperationException(collectionName, guid,
                "Original mongo exception:" + e.getMessage());
    }
}

From source file:edu.wayne.cs.fms.controller.CRUD.java

public static void Delete(String id, MongoClient mongoClient) {
    ObjectId oId = new ObjectId(id);
    BasicDBObject query = new BasicDBObject("_id", oId);
    //MongoClient mongoClient = Connector.connect("localhost", 27017);
    DB db = mongoClient.getDB("project");
    DBCollection flight = db.getCollection("flight");
    System.out.println(query);/*  w  w  w  .  ja va 2  s .c o m*/
    flight.remove(query);
    //mongoClient.close();
}