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:applango.common.services.DB.mongo.mongoDB.java

public static DBObject removeRecordsFromDB(Applango applango, DBCollection coll) {
    logger.info("Remove all records with customerId : " + applango.getUsername());
    String jsonCustomer = "{'customerId' : '" + applango.getCustomerForoAuth() + "'}";
    DBObject dbObjectRecordQuery = (DBObject) JSON.parse(jsonCustomer);
    if (!(coll.count(dbObjectRecordQuery) == 0)) {
        coll.remove(dbObjectRecordQuery, WriteConcern.ACKNOWLEDGED);

    }/*from ww w  .  j a  v a  2s.co m*/
    return dbObjectRecordQuery;
}

From source file:br.bireme.scl.BrokenLinks.java

License:Open Source License

private static boolean saveRecord(final String mstName, final int id, final String url, final String err,
        final int urlTag, final List<Integer> ccsFlds, final Master mst, final DBCollection coll,
        final DBCollection hcoll, final Map<Integer, Map<String, Integer>> occMap)
        throws BrumaException, IOException {
    assert mstName != null;
    assert id > 0;
    assert url != null;
    assert urlTag > 0;
    assert err != null;
    assert ccsFlds != null;
    assert mst != null;
    assert coll != null;
    assert hcoll != null;
    assert occMap != null;

    final Record rec = mst.getRecord(id);
    if (!rec.isActive()) {
        //throw new BrumaException("not active record mfn=" + id);
        System.err.println("WARNING: record[" + id + "] is not active. " + "Ignoring it!");
        return false;
    }//from  w  w w . j  ava 2s  .c  om

    final List<Field> urls = rec.getFieldList(urlTag);
    final Date now = new Date();
    Date date;

    Map<String, Integer> fldMap = occMap.get(id);
    if (fldMap == null) {
        fldMap = new HashMap<String, Integer>();
        occMap.put(id, fldMap);
    }

    final int occ = nextOcc(url, urls, fldMap);
    if (occ == -1) {
        System.err.println("url[" + url + "] not found. mfn=" + id);
        //throw new IOException("url[" + url + "] not found. mfn=" + id);                
        return false;
    }

    final BasicDBObject query = new BasicDBObject(ID_FIELD, id + "_" + occ);
    final boolean ret;
    if (fixedRecently(hcoll, query, now, 60)) {
        ret = false;
    } else {
        final BasicDBObject obj = (BasicDBObject) coll.findOne(query);
        if (obj == null) {
            date = now;
        } else {
            date = obj.getDate(LAST_UPDATE_FIELD);
            if (date == null) {
                date = obj.getDate(DATE_FIELD);
            } else {
                final WriteResult wr = coll.remove(obj, WriteConcern.ACKNOWLEDGED);
                if (!wr.getCachedLastError().ok()) {
                    //TODO
                }
                date = obj.getDate(DATE_FIELD);
            }
        }
        final String url_d = EncDecUrl.decodeUrl(url);
        final String url_d_l = (url_d.length() >= 900) ? url_d.substring(0, 900) + "..." : url_d;
        final String url_l = (url.length() > 900) ? url.substring(0, 900) + "..." : url;
        final BasicDBObject doc = new BasicDBObject();
        doc.put(DATE_FIELD, date);
        doc.put(LAST_UPDATE_FIELD, now);
        doc.put(MST_FIELD, mstName);
        doc.put(ID_FIELD, id + "_" + occ);
        doc.put(BROKEN_URL_FIELD, url_l);
        doc.put(PRETTY_BROKEN_URL_FIELD, url_d_l);
        doc.put(MSG_FIELD, err);
        doc.put(CENTER_FIELD, getCCS(rec, ccsFlds));

        final WriteResult wres = coll.save(doc, WriteConcern.ACKNOWLEDGED);
        ret = wres.getCachedLastError().ok();
    }
    return ret;
}

From source file:br.bireme.scl.BrokenLinks.java

License:Open Source License

private static boolean removeOldDocs(final DBCollection coll) {
    assert coll != null;

    final Date now = new Date();
    final DBCursor cursor = coll.find();
    boolean ret = true;

    while (cursor.hasNext()) {
        final BasicDBObject obj = (BasicDBObject) cursor.next();
        final Date auxDate = obj.getDate(LAST_UPDATE_FIELD);
        if ((auxDate == null) || (now.getTime() - auxDate.getTime()) > 60 * 60 * 1000) {
            final WriteResult wr = coll.remove(obj, WriteConcern.ACKNOWLEDGED);
            ret = ret && wr.getCachedLastError().ok();
        }/*from  w w w  .  j  a va2 s .  co  m*/
    }
    return ret;
}

From source file:br.bireme.scl.MongoOperations.java

License:Open Source License

public static boolean updateDocument(final DBCollection coll, final DBCollection hcoll, final String docId,
        final String fixedUrl, final String user, final boolean automatic) throws IOException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }//from   w  w w  .j  ava2  s  .  c  o m
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    if (docId == null) {
        throw new NullPointerException("docId");
    }
    if (fixedUrl == null) {
        throw new NullPointerException("fixedUrl");
    }
    if (user == null) {
        throw new NullPointerException("user");
    }
    if (fixedUrl.length() >= 900) {
        throw new IOException("fixedUrl is too long >= 900. [" + fixedUrl + "]");
    }

    final BasicDBObject query = new BasicDBObject(ID_FIELD, docId);
    final BasicDBObject doc = (BasicDBObject) coll.findOne(query);

    if (doc == null) {
        throw new IOException("document not found id[" + docId + "]");
    }

    final BasicDBList lsthdoc;
    BasicDBObject hdoc = (BasicDBObject) hcoll.findOne(query);
    if (hdoc == null) {
        hdoc = new BasicDBObject();
        hdoc.append(ID_FIELD, docId);
        hdoc.append(MST_FIELD, (String) doc.get(MST_FIELD));
        hdoc.append(DATE_FIELD, (Date) doc.get(DATE_FIELD));
        lsthdoc = new BasicDBList();
        hdoc.append(ELEM_LST_FIELD, lsthdoc);
    } else {
        lsthdoc = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
    }

    final String brokenUrl = doc.getString(BROKEN_URL_FIELD);
    final String brokenUrl_D = EncDecUrl.decodeUrl(brokenUrl);
    final String fixedUrl_E = EncDecUrl.encodeUrl(fixedUrl, CODEC, false);
    //final String fixedUrl_D = EncDecUrl.decodeUrl(fixedUrl);
    final BasicDBObject hcurdoc = new BasicDBObject();
    hcurdoc.append(BROKEN_URL_FIELD, brokenUrl).append(PRETTY_BROKEN_URL_FIELD, brokenUrl_D)
            .append(FIXED_URL_FIELD, fixedUrl_E).append(MSG_FIELD, (String) doc.get(MSG_FIELD))
            .append(CENTER_FIELD, (BasicDBList) doc.get(CENTER_FIELD)).append(AUTO_FIX_FIELD, automatic)
            .append(EXPORTED_FIELD, false).append(LAST_UPDATE_FIELD, new Date()).append(USER_FIELD, user);

    lsthdoc.add(0, hcurdoc);

    final boolean ret1 = coll.remove(doc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    final boolean ret2 = hcoll.save(hdoc).getLastError().ok();

    return ret1 && ret2;
}

From source file:br.bireme.scl.MongoOperations.java

License:Open Source License

public static boolean undoUpdateDocument(final DBCollection coll, final DBCollection hcoll, final String docId,
        final boolean updateBrokenColl) throws IOException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }//w ww.  j a  v  a2s. co m
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    if (docId == null) {
        throw new NullPointerException("docId");
    }

    final BasicDBObject query = new BasicDBObject(ID_FIELD, docId);
    final BasicDBObject hdoc = (BasicDBObject) hcoll.findOne(query);

    if (hdoc == null) {
        throw new IOException("document not found id[" + docId + "]");
    }
    final BasicDBList lst = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
    final BasicDBObject hcurdoc = (BasicDBObject) lst.remove(0);
    if (hcurdoc == null) {
        throw new IOException("document last element found. Id[" + docId + "]");
    }
    final BasicDBObject doc = new BasicDBObject();
    doc.put(DATE_FIELD, hdoc.get(DATE_FIELD));
    doc.put(LAST_UPDATE_FIELD, hcurdoc.get(LAST_UPDATE_FIELD));
    doc.put(MST_FIELD, hdoc.get(MST_FIELD));
    doc.put(ID_FIELD, docId);
    doc.put(BROKEN_URL_FIELD, hcurdoc.get(BROKEN_URL_FIELD));
    doc.put(PRETTY_BROKEN_URL_FIELD, hcurdoc.get(PRETTY_BROKEN_URL_FIELD));
    doc.put(MSG_FIELD, hcurdoc.get(MSG_FIELD));
    doc.put(CENTER_FIELD, hcurdoc.get(CENTER_FIELD));

    final boolean ret1 = updateBrokenColl ? coll.save(doc).getLastError().ok() : true;
    final boolean ret2;

    if (lst.isEmpty()) {
        ret2 = hcoll.remove(query, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    } else {
        ret2 = hcoll.save(hdoc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    }

    return ret1 && ret2;
}

From source file:br.bireme.scl.MongoOperations.java

License:Open Source License

public static boolean undoUpdateDocument2(final DBCollection coll, final DBCollection hcoll,
        final String fromDate) throws IOException, ParseException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }//from w  w w .j  a v a  2s.  c o  m
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    final SimpleDateFormat simple = new SimpleDateFormat("yyyyMMdd");
    final Date date = (fromDate == null) ? new Date(0) : simple.parse(fromDate);
    final String updated = ELEM_LST_FIELD + ".0." + LAST_UPDATE_FIELD;
    final BasicDBObject qdate = new BasicDBObject("$gte", date);
    final BasicDBObject query = new BasicDBObject(updated, qdate);
    final BasicDBObject sort = new BasicDBObject(updated, -1);
    final DBCursor cursor = coll.find(query).sort(sort);

    boolean ret = true;

    while (cursor.hasNext()) {
        final BasicDBObject hdoc = (BasicDBObject) cursor.next();
        final BasicDBList lst = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
        final BasicDBObject hcurdoc = (BasicDBObject) lst.remove(0);
        if (hcurdoc == null) {
            throw new IOException("document last element found.");
        }
        final BasicDBObject doc = new BasicDBObject();
        doc.put(DATE_FIELD, hdoc.get(DATE_FIELD));
        doc.put(LAST_UPDATE_FIELD, hcurdoc.get(LAST_UPDATE_FIELD));
        doc.put(MST_FIELD, hdoc.get(MST_FIELD));
        doc.put(ID_FIELD, hdoc.get(ID_FIELD));
        doc.put(BROKEN_URL_FIELD, hcurdoc.get(BROKEN_URL_FIELD));
        doc.put(PRETTY_BROKEN_URL_FIELD, hcurdoc.get(PRETTY_BROKEN_URL_FIELD));
        doc.put(MSG_FIELD, hcurdoc.get(MSG_FIELD));
        doc.put(CENTER_FIELD, hcurdoc.get(CENTER_FIELD));

        final boolean ret1 = coll.save(doc).getLastError().ok();
        final boolean ret2;

        if (lst.isEmpty()) {
            ret2 = hcoll.remove(query, WriteConcern.ACKNOWLEDGED).getLastError().ok();
        } else {
            ret2 = hcoll.save(hdoc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
        }
        final boolean auxret = (ret1 && ret2);
        if (!auxret) {
            System.err.println("doc[" + hdoc.get(ID_FIELD) + "] write error");
        }
        ret &= auxret;
    }

    return ret;
}

From source file:br.bireme.scl.UndoUpdate.java

License:Open Source License

private static void undo(final String host, final int port, final String database, final String fromDate,
        final String docId) throws UnknownHostException, ParseException {
    assert host != null;
    assert port > 0;
    assert database != null;
    assert (fromDate != null || docId != null);

    final MongoClient client = new MongoClient(host, port);
    final DB db = client.getDB(database);
    final DBCollection from_coll = db.getCollection(HISTORY_COL);
    final DBCollection to_coll = db.getCollection(BROKEN_LINKS_COL);
    final String prefix = ELEM_LST_FIELD + ".0.";
    final BasicDBObject query;

    if (fromDate == null) {
        query = new BasicDBObject("_id", docId);
    } else {//from w w w.j a  v a 2  s .  co m
        final SimpleDateFormat simple = new SimpleDateFormat(
                "yyyyMMdd" + (fromDate.contains(":") ? "-HH:mm:ss" : ""));
        final Date fDate = simple.parse(fromDate);
        query = new BasicDBObject(prefix + LAST_UPDATE_FIELD, new BasicDBObject("$gte", fDate));
    }
    final DBCursor cursor = from_coll.find(query);
    int total = 0;
    int reverted = 0;

    System.out.println("host=" + host);
    System.out.println("port=" + port);
    System.out.println("database=" + database);
    if (fromDate == null) {
        System.out.println("doc id=" + docId);
    } else {
        System.out.println("from date=" + fromDate);
    }
    System.out.println("found=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc_from = (BasicDBObject) cursor.next();
        final BasicDBObject doc_to = new BasicDBObject(doc_from);
        final String id = doc_from.getString(ID_FIELD);
        final BasicDBList list = (BasicDBList) doc_from.get(ELEM_LST_FIELD);
        final BasicDBObject elem = (BasicDBObject) list.get(0);
        final Date date = elem.getDate(LAST_UPDATE_FIELD);

        doc_to.put(LAST_UPDATE_FIELD, date);
        doc_to.put(BROKEN_URL_FIELD, elem.getString(BROKEN_URL_FIELD));
        doc_to.put(MSG_FIELD, elem.getString(MSG_FIELD));
        doc_to.put(CENTER_FIELD, elem.get(CENTER_FIELD));
        doc_to.removeField(ELEM_LST_FIELD);

        final WriteResult wr = to_coll.save(doc_to, WriteConcern.ACKNOWLEDGED);
        if (wr.getCachedLastError().ok()) {
            final WriteResult wr2 = from_coll.remove(doc_from, WriteConcern.ACKNOWLEDGED);
            if (wr2.getCachedLastError().ok()) {
                reverted++;
                System.out.println("+++id=" + id + " date=" + date);
            } else {
                System.err.println("Document[" + id + "] delete error.");
            }
        } else {
            System.err.println("Document[" + id + "] update error.");
        }
        total++;
    }
    cursor.close();

    System.out.println("total/undo: " + total + "/" + reverted);
}

From source file:ch.agent.crnickl.mongodb.WriteMethodsForProperty.java

License:Apache License

/**
 * Delete the property./*w w  w . j av  a 2  s.c om*/
 * If deleting fails throw an exception.
 * 
 * @param prop a property
 * @param policy a schema updating policy
 * @throws T2DBException
 */
public <T> void deleteProperty(Property<T> prop, SchemaUpdatePolicy policy) throws T2DBException {
    boolean done = false;
    Throwable cause = null;
    Surrogate s = prop.getSurrogate();
    MongoDatabase database = (MongoDatabase) s.getDatabase();
    try {
        check(Permission.MODIFY, prop);
        // dangerous update! see comment in MongoDatabase.sleep
        policy.willDelete(prop);
        Property<T> original = database.getReadMethodsForProperty().getProperty(s);
        DBCollection coll = getMongoDB(s).getProperties();
        coll.remove(asQuery(s.getId()), WriteConcern.SAFE);
        database.sleep();
        try {
            policy.willDelete(original);
        } catch (T2DBException e) {
            createProperty(original);
            throw e;
        }
        done = true;
    } catch (Exception e) {
        cause = e;
    } finally {
    }
    if (!done || cause != null)
        throw T2DBMsg.exception(cause, E.E20115, prop.getName());
}

From source file:ch.agent.crnickl.mongodb.WriteMethodsForSchema.java

License:Apache License

/**
 * Delete a schema from the database./*from   w  ww .  jav a 2 s.  co m*/
 * Throw an exception if the operation cannot be done.
 * 
 * @param schema a schema
 * @param policy a schema udpdating policy
 * @throws T2DBException
 */
public void deleteSchema(UpdatableSchema schema, SchemaUpdatePolicy policy) throws T2DBException {
    boolean done = false;
    Throwable cause = null;
    Surrogate s = schema.getSurrogate();
    MongoDatabase database = (MongoDatabase) s.getDatabase();
    try {
        check(Permission.MODIFY, schema);
        policy.willDelete(schema);
        UpdatableSchema original = database.getReadMethodsForSchema().getSchema(s);
        DBCollection coll = getMongoDB(s).getSchemas();
        coll.remove(asQuery(s.getId()), WriteConcern.SAFE);
        database.sleep();
        try {
            policy.willDelete(schema);
        } catch (T2DBException e) {
            // Oops! referential integrity broken!
            createSchema(original);
            throw e;
        }
        done = true;
    } catch (Exception e) {
        cause = e;
    } finally {
    }
    if (!done || cause != null) {
        throw T2DBMsg.exception(cause, E.E30123, schema.getName());
    }
}

From source file:ch.agent.crnickl.mongodb.WriteMethodsForValueType.java

License:Apache License

/**
 * Delete a value type from the database.
 * Throw an exception if the operation fails.
 * /*from w  w w  .  jav  a 2 s .  co m*/
 * @param vt a value type
 * @param policy a schema udpdating policy
 * @throws T2DBException
 */
public <T> void deleteValueType(ValueType<T> vt, SchemaUpdatePolicy policy) throws T2DBException {
    boolean done = false;
    Throwable cause = null;
    Surrogate s = vt.getSurrogate();
    MongoDatabase database = (MongoDatabase) s.getDatabase();
    try {
        check(Permission.MODIFY, vt);
        policy.willDelete(vt);
        ValueType<T> original = database.getReadMethodsForValueType().getValueType(s);
        DBCollection coll = getMongoDB(s).getValueTypes();
        coll.remove(asQuery(s.getId()), WriteConcern.SAFE); // ??? REPLICA_SAFE --> MongoException("norepl");
        database.sleep();
        try {
            policy.willDelete(original);
        } catch (T2DBException e) {
            // Oops! referential integrity broken!
            createValueType(original);
            throw e;
        }
        done = true;
    } catch (Exception e) {
        cause = e;
    } finally {
    }
    if (!done || cause != null) {
        throw T2DBMsg.exception(cause, E.E10145, vt.getName());
    }
}