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) 

Source Link

Document

Modify an existing document.

Usage

From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java

License:Apache License

/**
 * @see org.apache.sling.api.resource.ModifyingResourceProvider#commit(ResourceResolver)
 *//*  w w w  . ja va  2  s  .co  m*/
public void commit(final ResourceResolver resolver) throws PersistenceException {
    try {
        for (final String deleted : this.deletedResources) {
            final String[] info = this.extractResourceInfo(deleted);

            // check if the collection still exists
            final DBCollection col = this.getCollection(info[0]);
            if (col != null) {
                if (col.findAndRemove(QueryBuilder.start(getPROP_PATH()).is(info[1]).get()) != null) {
                    this.context.notifyRemoved(info);
                }
            }
        }
        for (final MongoDBResource changed : this.changedResources.values()) {

            final DBCollection col = this.context.getDatabase().getCollection(changed.getCollection());
            if (col != null) {
                final String[] info = new String[] { changed.getCollection(),
                        changed.getProperties().get(getPROP_PATH()).toString() };
                // create or update?
                if (changed.getProperties().get(PROP_ID) != null) {
                    col.update(QueryBuilder.start(getPROP_PATH())
                            .is(changed.getProperties().get(getPROP_PATH())).get(), changed.getProperties());
                    this.context.notifyUpdated(info);
                } else {
                    // create
                    col.save(changed.getProperties());
                    this.context.notifyUpdated(info);
                }
            } else {
                throw new PersistenceException("Unable to create collection " + changed.getCollection(), null,
                        changed.getPath(), null);
            }
        }
    } finally {
        this.revert(resolver);
    }
}

From source file:org.aw20.mongoworkbench.command.UpdateMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);/*from  ww  w . j  a v  a2  s  .  c  o m*/
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("updateArg"))
        throw new Exception("no update document");

    List argList = (List) cmdMap.get("updateArg");
    if (argList.size() == 1)
        throw new Exception("not enough parameters; db.collection.update(query, update, <upsert>, <multi>)");

    DBCollection collection = db.getCollection(sColl);

    db.requestStart();
    WriteResult writeresult = null;
    try {

        if (argList.size() == 2) {

            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)));

        } else if (argList.size() == 3) {

            boolean upsert = StringUtil.toBoolean(argList.get(2), false);
            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)), upsert, false);

        } else if (argList.size() == 4) {

            boolean upsert = StringUtil.toBoolean(argList.get(2), false);
            boolean multi = StringUtil.toBoolean(argList.get(3), false);
            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)), upsert, multi);

        } else
            throw new Exception("too many parameters; db.collection.update(query, update, <upsert>, <multi>)");

    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Updated: updatedExisting=" + mwriteresult.get("updatedExisting") + "; documentsUpdated="
            + mwriteresult.get("n"));
}

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

License:Open Source License

@Override
public void updateFieldsInExistingDocUsingJSON(String database, JsonObject keytoSearch,
        JsonObject jsonObjectToUpdate, String collection) throws TotalADSDBMSException {

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

    BasicDBObject query = (BasicDBObject) JSON.parse(keytoSearch.toString());
    // new BasicDBObject();
    // query.put("name", "MongoDB");

    BasicDBObject newDocument = (BasicDBObject) JSON.parse(jsonObjectToUpdate.toString());
    // newDocument.put("name", "MongoDB-updated");

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", newDocument); //$NON-NLS-1$

    col.update(query, updateObj);

}

From source file:org.einherjer.week2.samples.UpdateRemoveSample.java

License:Apache License

private static void scratch(DBCollection collection) {
    //whole document replacement, remember the _id field is not replaces so in this case, since _id was the only field, age gets added
    //  if we do this a second time with gender:"F" instead of age:24 the document would end up with _id and gender fields, and age would be gone
    collection.update(new BasicDBObject("_id", "alice"), new BasicDBObject("age", 24));

    //sets adds the gender field to the existing _id and age fields
    collection.update(new BasicDBObject("_id", "alice"),
            new BasicDBObject("$set", new BasicDBObject("gender", "F")));

    //upsert ("frank" didn't exist originally, so this update actually performs an insert)
    collection.update(new BasicDBObject("_id", "frank"),
            new BasicDBObject("$set", new BasicDBObject("age", 24)), true, false);

    //multi document update
    collection.update(new BasicDBObject(), new BasicDBObject("$set", new BasicDBObject("title", "Dr")), false,
            true);//from  w  ww  .ja v  a2  s  . com

    collection.remove(new BasicDBObject("_id", "frank"));
}

From source file:org.exist.mongodb.xquery.mongodb.collection.Update.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/*  w  w w . j a va 2  s  .  co  m*/
        // Verify clientid and get client
        String mongodbClientId = args[0].itemAt(0).getStringValue();
        MongodbClientStore.getInstance().validate(mongodbClientId);
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);

        // Get parameters
        String dbname = args[1].itemAt(0).getStringValue();
        String collection = args[2].itemAt(0).getStringValue();

        // Get database
        DB db = client.getDB(dbname);
        DBCollection dbcol = db.getCollection(collection);

        // Get data
        BasicDBObject criterium = (BasicDBObject) JSON.parse(args[3].itemAt(0).getStringValue());
        BasicDBObject modification = (BasicDBObject) JSON.parse(args[4].itemAt(0).getStringValue());

        Boolean upsert = (args.length >= 6) ? args[5].itemAt(0).toJavaObject(Boolean.class) : null;

        Boolean multi = (args.length >= 7) ? args[6].itemAt(0).toJavaObject(Boolean.class) : null;

        // Execute update
        WriteResult update = (upsert == null) ? dbcol.update(criterium, modification)
                : dbcol.update(criterium, modification, upsert, multi);

        return new StringValue(update.toString());

    } catch (MongoCommandException ex) {
        // TODO return as value?
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0005, ex.getMessage());

    } catch (JSONParseException ex) {
        String msg = "Invalid JSON data: " + ex.getMessage();
        LOG.error(msg);
        throw new XPathException(this, MongodbModule.MONG0004, msg);

    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);

    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage());

    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        throw new XPathException(this, MongodbModule.MONG0003, t.getMessage());
    }

}

From source file:org.fastmongo.odm.repository.MongoTemplate.java

License:Apache License

@Override
public WriteResult update(String collectionName, Query query, DBObject o) {
    DBCollection collection = getCollection(collectionName);
    return collection.update(query.toDbObject(), o);
}

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

License:Open Source License

/**
 * Updates the specified object in the object set. 
 * <p>// www .j av  a2  s .c om
 * This implementation requires MVCC and hence enforces that clients state what revision they expect 
 * to be updating
 * 
 * If successful, this method updates metadata properties within the passed object,
 * including: a new {@code _rev} value for the revised object's version
 *
 * @param fullId the identifier of the object to be put, or {@code null} to request a generated identifier.
 * @param rev the version of the object to update; or {@code null} if not provided.
 * @param obj the contents of the object to put in the object set.
 * @throws ConflictException if version is required but is {@code null}.
 * @throws ForbiddenException if access to the object is forbidden.
 * @throws NotFoundException if the specified object could not be found. 
 * @throws PreconditionFailedException if version did not match the existing object in the set.
 * @throws BadRequestException if the passed identifier is invalid
 */
@Override
public void update(String fullId, String rev, Map<String, Object> obj) throws ObjectSetException {

    String localId = getLocalId(fullId);
    String type = getObjectType(fullId, false);

    if (rev == null) {
        throw new ConflictException("Object passed into update does not have revision it expects set.");
    } else {
        DocumentUtil.parseVersion(rev);
        obj.put(DocumentUtil.TAG_REV, rev);
    }

    DBCollection collection = getCollection(type);
    DBObject existingDoc = predefinedQueries.getByID(localId, collection);
    if (existingDoc == null) {
        throw new NotFoundException("Update on object " + fullId + " could not find existing object.");
    }

    obj.remove(DocumentUtil.TAG_ID);
    obj.put(DocumentUtil.MONGODB_PRIMARY_KEY, localId);
    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start(obj);
    DBObject jo = builder.get();
    jo = DocumentUtil.normalizeForWrite(jo);
    WriteResult res = collection.update(new BasicDBObject(DocumentUtil.TAG_ID, localId), jo);
    logger.trace("Updated doc for id {} to save {}", fullId, jo);
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.MongoDbSaveAccessImpl.java

License:Apache License

protected void updateWithOptimisticLocking(T obj, DBObject dbObj) {
    Long version = (Long) dbObj.get("version");
    DBObject q = new BasicDBObject();
    q.put("_id", dbObj.get("_id"));
    // version in db must be same as old version
    q.put("version", version);
    Long newVersion;/*from  ww  w.ja v a  2 s.  c o  m*/
    if (version == null) {
        newVersion = 1L;
    } else {
        newVersion = version + 1;
    }
    dbObj.put("version", newVersion);
    DBCollection dbCollection = getDBCollection();
    dbCollection.update(q, dbObj);
    DBObject lastError = dbCollection.getDB().getLastError();

    if (lastError.containsField("updatedExisting") && Boolean.FALSE.equals(lastError.get("updatedExisting"))) {
        throw new OptimisticLockingException(
                "Optimistic locking violation. Object was updated by someone else.");
    }

    checkLastError();
    IdReflectionUtil.internalSetVersion(obj, newVersion);
}

From source file:org.graylog2.indexer.ranges.MongoIndexRangeService.java

License:Open Source License

public boolean markAsMigrated(String index) {
    final DB db = mongoConnection.getDatabase();
    final DBCollection collection = db.getCollection(COLLECTION_NAME);

    final DBObject updatedData = new BasicDBObject("$set", new BasicDBObject(FIELD_MIGRATED, true));
    final DBObject searchQuery = new BasicDBObject("index", index);
    final WriteResult result = collection.update(searchQuery, updatedData);

    return result.isUpdateOfExisting();
}

From source file:org.graylog2.streams.StreamImpl.java

License:Open Source License

public void setLastAlarm(int timestamp, Core server) {
    DBCollection coll = server.getMongoConnection().getDatabase().getCollection("streams");
    DBObject query = new BasicDBObject();
    query.put("_id", this.id);

    DBObject stream = coll.findOne(query);
    stream.put("last_alarm", timestamp);

    coll.update(query, stream);
}