Example usage for com.mongodb DBCollection update

List of usage examples for com.mongodb DBCollection update

Introduction

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

Prototype

public WriteResult update(final DBObject query, final DBObject update, final boolean upsert,
        final boolean multi) 

Source Link

Document

Modify an existing document or documents in collection.

Usage

From source file:no.pritest.restapi.MongoChangeDataDAO.java

License:Open Source License

@Override
public void update(ChangeData changeData) {
    try {//from  www .j ava  2  s .  c  o  m
        DB db = MongoDBProvider.getInstance().getDB();
        DBCollection coll = db.getCollection("changedata");

        String processedSource = processSource(changeData.getSource());

        BasicDBObject query = new BasicDBObject();
        query.put("source", processedSource);

        BasicDBObject object = new BasicDBObject();
        object.put("source", processedSource);
        object.put("lastChange", changeData.getLastChange());

        coll.update(query, object, true, false);

    } catch (MongoException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

From source file:no.pritest.restapi.MongoTestDataDAO.java

License:Open Source License

@Override
public void update(TestData testData) {
    try {/*  w w w. j a  v a 2  s  .c  o m*/
        DB db = MongoDBProvider.getInstance().getDB();
        DBCollection coll = db.getCollection("testdata");

        BasicDBObject query = new BasicDBObject();
        query.put("source", testData.getClassName());

        BasicDBObject object = new BasicDBObject();
        object.put("source", testData.getClassName());
        object.put("fails", testData.getFails());

        coll.update(query, object, true, false);

    } catch (MongoException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.chemistry.opencmis.mongodb.MongodbUtils.java

License:Apache License

public void moveNode(BasicDBObject node, BasicDBObject newParent, DBCollection collection) {

    // Get the left and right values
    Long originalLeft = node.getLong("left");
    Long originalRight = node.getLong("right");
    Long subtreeWidth = originalRight - originalLeft;

    // Compute the new left and right values for the nodeToMove
    Long newLeft = newParent.getLong("right");
    Long newRight = newParent.getLong("right") + subtreeWidth;

    // Make space for the new subtree under the new parent
    collection.update(
            new BasicDBObject().append("right", new BasicDBObject().append("$gte", newParent.get("right"))),
            new BasicDBObject().append("$inc", new BasicDBObject().append("right", subtreeWidth + 1)), false,
            true);/*w  w  w  . java 2 s.c om*/

    collection.update(
            new BasicDBObject().append("left", new BasicDBObject().append("$gte", newParent.get("right"))),
            new BasicDBObject().append("$inc", new BasicDBObject().append("left", subtreeWidth + 1)), false,
            true);

    // Re-fetch the node to move, since the left and right values may have changed
    node = (BasicDBObject) collection.findOne(new BasicDBObject().append("_id", node.get("_id")));

    Long difference = node.getLong("left") - newLeft;
    // Move the old subtree into a new location
    collection.update(
            new BasicDBObject().append("left", new BasicDBObject().append("$gte", node.getLong("left")))
                    .append("right", new BasicDBObject().append("$lte", node.getLong("right"))),
            new BasicDBObject().append("$inc",
                    new BasicDBObject().append("left", 0 - difference).append("right", 0 - difference)),
            false, true);

    // Remove empty space from the parent
    //db.test.update({left:nodeToMove.left-1, right:nodeToMove.right+1}, {right:nodeToMove.left});
    collection.update(new BasicDBObject().append("right", new BasicDBObject().append("$gte", node.get("left"))),
            new BasicDBObject().append("$inc", new BasicDBObject().append("right", 0 - subtreeWidth - 1)),
            false, true);
    collection.update(new BasicDBObject().append("left", new BasicDBObject().append("$gte", node.get("left"))),
            new BasicDBObject().append("$inc", new BasicDBObject().append("left", 0 - subtreeWidth - 1)), false,
            true);
}

From source file:org.apache.felix.useradmin.mongodb.MongoDBStore.java

License:Apache License

@Override
public void roleChanged(UserAdminEvent event) {
    if (UserAdminEvent.ROLE_CHANGED == event.getType()) {
        // Only the changes are interesting, as the creation and 
        // removal are already caught by #addRole and #removeRole.... 
        Role changedRole = event.getRole();

        try {//  w ww. ja  v a  2s. c o m
            DBCollection coll = getCollection();

            DBObject query = getTemplateObject(changedRole);
            DBObject update = m_helper.serializeUpdate(changedRole);

            WriteResult result = coll.update(query, update, false /* upsert */, false /* multi */);

            if (result.getLastError() != null) {
                result.getLastError().throwOnError();
            }
        } catch (MongoException e) {
            m_log.log(LogService.LOG_WARNING, "Failed to update changed role: " + changedRole.getName(), e);
        }
    }
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java

License:Apache License

@Override
public <T extends Document> void update(Collection<T> collection, List<String> keys, UpdateOp updateOp) {
    log("update", keys, updateOp);
    UpdateUtils.assertUnconditional(updateOp);
    DBCollection dbCollection = getDBCollection(collection);
    QueryBuilder query = QueryBuilder.start(Document.ID).in(keys);
    // make sure we don't modify the original updateOp
    updateOp = updateOp.copy();//from  w w  w . j  ava 2  s. co  m
    DBObject update = createUpdate(updateOp, false);
    final Stopwatch watch = startWatch();
    try {
        Map<String, NodeDocument> cachedDocs = Collections.emptyMap();
        if (collection == Collection.NODES) {
            cachedDocs = Maps.newHashMap();
            for (String key : keys) {
                cachedDocs.put(key, nodesCache.getIfPresent(key));
            }
        }
        try {
            dbCollection.update(query.get(), update, false, true);
            if (collection == Collection.NODES) {
                Map<String, ModificationStamp> modCounts = getModStamps(
                        filterValues(cachedDocs, notNull()).keySet());
                // update cache
                for (Entry<String, NodeDocument> entry : cachedDocs.entrySet()) {
                    // the cachedDocs is not empty, so the collection = NODES
                    Lock lock = nodeLocks.acquire(entry.getKey());
                    try {
                        ModificationStamp postUpdateModStamp = modCounts.get(entry.getKey());
                        if (postUpdateModStamp != null && entry.getValue() != null
                                && entry.getValue() != NodeDocument.NULL
                                && Long.valueOf(postUpdateModStamp.modCount - 1)
                                        .equals(entry.getValue().getModCount())) {
                            // post update modCount is one higher than
                            // what we currently see in the cache. we can
                            // replace the cached document
                            NodeDocument newDoc = applyChanges(Collection.NODES, entry.getValue(),
                                    updateOp.shallowCopy(entry.getKey()));
                            nodesCache.replaceCachedDocument(entry.getValue(), newDoc);
                        } else {
                            // make sure concurrently loaded document is
                            // invalidated
                            nodesCache.invalidate(entry.getKey());
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            }
        } catch (MongoException e) {
            // some documents may still have been updated
            // invalidate all documents affected by this update call
            for (String k : keys) {
                nodesCache.invalidate(k);
            }
            throw DocumentStoreException.convert(e);
        }
    } finally {
        stats.doneUpdate(watch.elapsed(TimeUnit.NANOSECONDS), collection, keys.size());
    }
}

From source file:org.apache.nutch.crawl.GeneratorJob2.java

License:Apache License

public int generateBatchId(Configuration conf, String batchId) {
    MongoClient mongoClient = null;/*from  w w  w . jav a 2  s .  co m*/
    try {
        mongoClient = new MongoClient(goraMongoAddress);
        DB db = mongoClient.getDB(goraMongoDb);
        String cId = conf.get(Nutch.CRAWL_ID_KEY);
        String collPrefix = "";
        if (org.apache.commons.lang3.StringUtils.isNoneEmpty(cId)) {
            collPrefix = cId + "_";
        }
        String crawlColl = collPrefix + "webpage";
        DBCollection collOps = db.getCollection(crawlColl);
        //update({"count":{$gt:20}},{$set:{"name":"c4"}},false,true)  
        BasicDBObject q = new BasicDBObject("batchId", null);

        DBObject set = new BasicDBObject("batchId", batchId);
        set.put("markers._gnmrk_", batchId);
        BasicDBObject o = new BasicDBObject("$set", set);
        WriteResult wr = collOps.update(q, o, false, true);
        long curTime = System.currentTimeMillis();
        //taotoxht add
        q = new BasicDBObject();
        q.append("fetchTime", new BasicDBObject().append(QueryOperators.GT, curTime));
        o = new BasicDBObject();
        o.append("$set", new BasicDBObject().append("fetchTime", curTime));
        collOps.update(q, o, false, true);

        return wr.getN();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;

    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }

}

From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java

License:Open Source License

/**
 * Inserts or updates (if already exists) an object in the form of JSON representation into the database. Any kind of complex
 *  data structure can be converted to JSON using gson library and passed to this function 
 * @param database Database name/*from  w w w  .ja v a2 s  .  c  om*/
 * @param jsonObject JSON Object
 * @param collection collection name
 */
public void insertOrUpdateUsingJSON(String database, JsonObject keytoSearch, JsonObject jsonObjectToUpdate,
        String collection) throws TotalADSDBMSException {
    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject docToUpdate = (BasicDBObject) JSON.parse(jsonObjectToUpdate.toString());

    BasicDBObject keyToSearch = (BasicDBObject) JSON.parse(keytoSearch.toString());

    WriteResult writeRes = coll.update(keyToSearch, docToUpdate, true, false);

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok())
        throw new TotalADSDBMSException("Error : " + cmdResult.getErrorMessage());

}

From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java

License:Open Source License

/**
 * This function is used to update the values of individual fields--specified by the replacementFieldsAndValue object--
 *  in documents--specified by the searchFieldsandValues object. Pass two objects of  classes that only has primitive data types
 *   as fields--no methods. Each object's fields' values  and their data types will be automatically extracted and used
 *   in the update. If no document matches the criteria then new document will be inserted
 * @param searchKeyAndItsValue Search fields
 * @param replacementFieldsAndValues Replacement fields
 * @param database Database name//  w  w  w . ja v  a2s .c o  m
 * @param collection Collection name
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public void replaceFields(Object searchKeyAndItsValue, Object replacementFieldsAndValues, String database,
        String collection) throws IllegalArgumentException, IllegalAccessException, TotalADSDBMSException {

    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject replacementDocument = new BasicDBObject();
    BasicDBObject setFieldValDocument = new BasicDBObject();

    extractKeysAndValuesfromTheObject(replacementFieldsAndValues, setFieldValDocument);

    replacementDocument.append("$set", setFieldValDocument);

    BasicDBObject searchQueryDocument = new BasicDBObject();
    //.append("hosting", "hostB");
    extractKeysAndValuesfromTheObject(searchKeyAndItsValue, searchQueryDocument);

    WriteResult writeRes = coll.update(searchQueryDocument, replacementDocument, true, false);

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok())
        throw new TotalADSDBMSException("Error : " + cmdResult.getErrorMessage());

}

From source file:org.eclipse.tracecompass.totalads.dbms.MongoDBMS.java

License:Open Source License

@Override
public void insertOrUpdateUsingJSON(String database, JsonObject keytoSearch, JsonObject jsonObjectToUpdate,
        String collection) throws TotalADSDBMSException {
    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject docToUpdate = (BasicDBObject) JSON.parse(jsonObjectToUpdate.toString());

    BasicDBObject keyToSearch = (BasicDBObject) JSON.parse(keytoSearch.toString());

    WriteResult writeRes = coll.update(keyToSearch, docToUpdate, true, false);

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok()) {
        throw new TotalADSDBMSException("Error : " + cmdResult.getErrorMessage()); //$NON-NLS-1$
    }/*from   w w  w  .java2 s .c  o m*/

}

From source file:org.fusesource.bai.backend.mongo.MongoDBBackend.java

License:Apache License

private void addToMetaCollection(AuditEvent ev) {
    DBObject filter = new BasicDBObject("_id", ev.getBreadCrumbId());
    DBObject dbo = new BasicDBObject("$addToSet",
            new BasicDBObject("routes", ev.getSourceContextId() + "." + ev.getSourceRouteId()));
    // possible collection names: eagleView, hawkView
    DBCollection collection = db.getCollection("exchangeXray");
    collection.update(filter, dbo, true, false);
}