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, final DBCollectionRemoveOptions options) 

Source Link

Document

Remove documents from a collection.

Usage

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

License:Apache License

@Override
protected void deleteEntry(String family, final Object key, final Object entry) {
    mongoTemplate.execute(new DbCallback<Object>() {
        public Object doInDB(DB con) throws MongoException, DataAccessException {
            DBCollection dbCollection = getCollection(con);

            DBObject dbo = createDBObjectWithKey(key);
            MongoSession mongoSession = (MongoSession) session;
            dbCollection.remove(dbo, mongoSession.getWriteConcern());
            return null;
        }/*from w ww.ja v  a2s .  c o m*/

        protected DBCollection getCollection(DB con) {
            return con.getCollection(getCollectionName(getPersistentEntity()));
        }
    });
}

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

License:LGPL

@Override
public void removeTuple(EntityKey key, TupleContext tupleContext) {
    DBCollection collection = getCollection(key);
    DBObject toDelete = prepareIdObject(key);
    WriteConcern writeConcern = getWriteConcern(tupleContext);

    collection.remove(toDelete, writeConcern);
}

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

License:LGPL

@Override
public void removeAssociation(AssociationKey key, AssociationContext associationContext) {
    AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy(key, associationContext);
    WriteConcern writeConcern = getWriteConcern(associationContext);

    if (storageStrategy == AssociationStorageStrategy.IN_ENTITY) {
        DBObject entity = this.prepareIdObject(key.getEntityKey());
        if (entity != null) {
            BasicDBObject updater = new BasicDBObject();
            addSubQuery("$unset", updater, key.getMetadata().getCollectionRole(), Integer.valueOf(1));
            DBObject dbObject = getEmbeddingEntity(key, associationContext);
            if (dbObject != null) {
                dbObject.removeField(key.getMetadata().getCollectionRole());
                getCollection(key.getEntityKey()).update(entity, updater, true, false, writeConcern);
            }/*  www . j  a  v  a  2s .co m*/
        }
    } else {
        DBCollection collection = getAssociationCollection(key, storageStrategy);
        DBObject query = associationKeyToObject(key, storageStrategy);

        int nAffected = collection.remove(query, writeConcern).getN();
        log.removedAssociation(nAffected);
    }
}

From source file:org.jumpmind.symmetric.io.MongoDatabaseWriter.java

License:Open Source License

@Override
protected LoadStatus delete(CsvData data, boolean useConflictDetection) {
    statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
    try {/*from ww w. j a va 2  s. c om*/
        DB db = clientManager.getDB(objectMapper.mapToDatabase(this.targetTable));
        DBCollection collection = db.getCollection(objectMapper.mapToCollection(this.targetTable));
        String[] columnNames = sourceTable.getColumnNames();
        Map<String, String> newData = data.toColumnNameValuePairs(columnNames, CsvData.ROW_DATA);
        Map<String, String> oldData = data.toColumnNameValuePairs(columnNames, CsvData.OLD_DATA);
        Map<String, String> pkData = data.toKeyColumnValuePairs(this.sourceTable);
        DBObject query = objectMapper.mapToDBObject(sourceTable, newData, oldData, pkData, true);
        WriteResult results = collection.remove(query, WriteConcern.ACKNOWLEDGED);
        if (results.getN() != 1) {
            log.warn("Attempted to remove a single object" + query.toString() + ".  Instead removed: "
                    + results.getN());
        }
        return LoadStatus.SUCCESS;
    } finally {
        statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
    }

}

From source file:org.qi4j.entitystore.mongodb.MongoMapEntityStoreMixin.java

License:Apache License

@Override
public void applyChanges(MapChanges changes) throws IOException {
    db.requestStart();/*  w w  w  .  j  ava  2  s .com*/
    final DBCollection entities = db.getCollection(collectionName);

    changes.visitMap(new MapChanger() {

        @Override
        public Writer newEntity(final EntityReference ref, EntityDescriptor entityDescriptor)
                throws IOException {
            return new StringWriter(1000) {

                @Override
                public void close() throws IOException {
                    super.close();

                    String jsonState = toString();
                    System.out.println("############################################");
                    try {
                        System.out.println(new JSONObject(jsonState).toString(2));
                    } catch (JSONException ex) {
                        ex.printStackTrace();
                    }
                    System.out.println("############################################");
                    DBObject bsonState = (DBObject) JSON.parse(jsonState);

                    BasicDBObject entity = new BasicDBObject();
                    entity.put(IDENTITY_COLUMN, ref.identity());
                    entity.put(STATE_COLUMN, bsonState);
                    entities.save(entity, writeConcern);
                }

            };
        }

        @Override
        public Writer updateEntity(final EntityReference ref, EntityDescriptor entityDescriptor)
                throws IOException {
            return new StringWriter(1000) {

                @Override
                public void close() throws IOException {
                    super.close();

                    DBObject bsonState = (DBObject) JSON.parse(toString());

                    BasicDBObject entity = new BasicDBObject();
                    entity.put(IDENTITY_COLUMN, ref.identity());
                    entity.put(STATE_COLUMN, bsonState);
                    entities.update(byIdentity(ref), entity, true, false, writeConcern);
                }

            };
        }

        @Override
        public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor)
                throws EntityNotFoundException {
            DBObject entity = entities.findOne(byIdentity(ref));
            if (entity == null) {
                throw new EntityNotFoundException(ref);
            }
            entities.remove(entity, writeConcern);
        }

    });

    db.requestDone();
}

From source file:org.s1.mongodb.cluster.MongoDBDDS.java

License:Apache License

@Override
public void runWriteCommand(CommandBean b) {
    if (Objects.isNullOrEmpty(b.getCollection())) {
        return;//from ww  w  .j av  a 2 s  .c  o  m
    }
    if (Objects.isNullOrEmpty(b.getEntity())) {
        return;
    }
    DBCollection coll = MongoDBConnectionHelper.getConnection(b.getDatabase()).getCollection(b.getCollection());

    if ("add".equals(b.getCommand()) || "set".equals(b.getCommand())) {
        if (b.getParams() == null) {
            return;
        }
        Map<String, Object> search = Objects.newHashMap("id", b.getEntity());
        b.getParams().put("id", b.getEntity());
        int n = coll.update(MongoDBFormat.fromMap(search), MongoDBFormat.fromMap(b.getParams()),
                b.getCommand().equals("add"), false, WriteConcern.FSYNC_SAFE).getN();
        if (LOG.isDebugEnabled())
            LOG.debug("MongoDB records(" + n + ") " + (b.getCommand().equals("add") ? "added" : "updated")
                    + ", " + b);
    } else if ("remove".equals(b.getCommand())) {
        Map<String, Object> search = Objects.newHashMap("id", b.getEntity());
        int n = coll.remove(MongoDBFormat.fromMap(search), WriteConcern.FSYNC_SAFE).getN();
        if (LOG.isDebugEnabled())
            LOG.debug("MongoDB records(" + n + ") removed, " + b);
    }
}

From source file:org.semispace.semimeter.dao.mongo.SemiMeterDaoMongo.java

License:Apache License

private void deleteOldMinutes(long before24h, long before180min, long before15min) {
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(before24h);/*from w  w w. java  2 s.c  o  m*/
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MINUTE, 0);
    long targetHour = cal.getTimeInMillis();

    DBCollection meterCollection = mongoTemplate.getCollection("meter");
    DBCursor result = meterCollection.find(new BasicDBObject(), new BasicDBObject("_id", 1));
    while (result.hasNext()) {
        DBObject doc = result.next();

        try {
            //start a new "session" for each document. not sure if this actually helps anything consistency-wise
            meterCollection.getDB().requestStart();

            //and fetch actual object (result only contains _id's)
            doc = meterCollection.findOne(doc); // TODO Double check

            log.trace("cleaning document : {}", doc);
            DBObject day = (DBObject) doc.get("day");
            //log.trace("day: {}", day);
            DBObject hours = (DBObject) day.get("hours");
            //log.trace("hours: {}", hours);
            Set<String> hrSet = new HashSet<String>();
            hrSet.addAll(hours.keySet());
            boolean docChanged = false;

            if (hrSet.isEmpty()) {
                log.trace("no hours in document, remove it: {}", doc);
                meterCollection.remove(new BasicDBObject("_id", doc.get("_id")), WriteConcern.UNACKNOWLEDGED);
            } else {
                for (String h : hrSet) {
                    long hourmillis = Long.valueOf(h);
                    log.trace("checking hour: {}", hourmillis);
                    if (hourmillis < targetHour) {
                        if (log.isTraceEnabled()) {
                            log.trace("removing hour " + h + " because it is older than target" + targetHour);
                        }
                        docChanged = true;
                        DBObject obj = (DBObject) hours.get(h);
                        day.put("count", (Integer) day.get("count") - (Integer) obj.get("count"));
                        hours.removeField(h);
                    } else if (hourmillis == targetHour) {
                        log.trace("current hour is targetHour, check minutes");
                        DBObject currentHour = (DBObject) hours.get(h);
                        DBObject minutes = (DBObject) currentHour.get("minutes");
                        Set<String> keys = new HashSet<String>();
                        keys.addAll(minutes.keySet());
                        for (String m : keys) {
                            long minutemillis = Long.valueOf(m);
                            log.trace("checking minute: {}", minutemillis);
                            if (minutemillis < before24h) {
                                if (log.isTraceEnabled()) {
                                    log.trace("removing minute " + minutemillis + " because it is older than "
                                            + before24h);
                                }

                                docChanged = true;
                                DBObject obj = (DBObject) minutes.get(m);
                                DBObject hourObj = (DBObject) hours.get(h);
                                day.put("count", (Integer) day.get("count") - (Integer) obj.get("count"));
                                hourObj.put("count",
                                        (Integer) hourObj.get("count") - (Integer) obj.get("count"));
                                minutes.removeField(m);
                            }
                        }
                        if (minutes.keySet().isEmpty()) {
                            log.trace("no more minutes, removing hour {}", h);
                            hours.removeField(h);
                            docChanged = true;
                        }
                    }
                }
            }

            docChanged |= updateTrendCounters(doc, before180min, before15min);

            if (docChanged) {
                meterCollection.save(doc);
            }
        } finally {
            meterCollection.getDB().requestDone();
        }
    }
}

From source file:org.semispace.semimeter.dao.mongo.SemiMeterDaoMongo.java

License:Apache License

private void deleteOldSums(long when) {
    DBCollection sumsCollection = mongoTemplate.getCollection("sums");
    DBCursor result = sumsCollection.find((DBObject) JSON.parse("{'time.ts': {'$lt': " + when + "}}"));

    while (result.hasNext()) {
        sumsCollection.remove(result.next(), WriteConcern.UNACKNOWLEDGED);
    }//  w w w .j  av  a 2  s  .c  om
}

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

License:Open Source License

public boolean remove(String username) {

    final DBCollection coll = coll();
    final BasicDBObject query = new BasicDBObject("username", username);
    WriteResult result = coll.remove(query, WriteConcern.SAFE);
    return (result.getN() != 0);
}

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

License:Apache License

@Override
protected void deleteEntry(String family, final Object key) {
    mongoTemplate.execute(new DbCallback<Object>() {
        @Override/*from  w w  w .  ja  va  2  s  . co  m*/
        public Object doInDB(DB con) throws MongoException, DataAccessException {
            DBCollection dbCollection = getCollection(con);

            DBObject dbo = new BasicDBObject();
            if (hasNumericalIdentifier) {
                dbo.put(MONGO_ID_FIELD, key);
            } else {
                dbo.put(MONGO_ID_FIELD, new ObjectId(key.toString()));
            }
            MongoSession mongoSession = (MongoSession) session;
            dbCollection.remove(dbo, mongoSession.getWriteConcern());
            return null;
        }

        protected DBCollection getCollection(DB con) {
            DBCollection dbCollection = con.getCollection(getCollectionName(getPersistentEntity()));
            return dbCollection;
        }
    });
}