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:org.socialhistoryservices.pid.database.dao.HandleDaoImpl.java

License:Open Source License

private void upsertHandle(String na, String pid, List<Handle> handles, int action) throws HandleException {

    // if the handle already exists, throw an exception
    final BasicDBObject query = new BasicDBObject("handle", pid);
    final List<HandleValue> currentValues = handleStorage.getHandleValues(pid);
    if (action == 2 && currentValues.size() == 0) {
        throw new HandleException(HandleException.HANDLE_DOES_NOT_EXIST,
                "The pid " + pid + " does not exist. Use the create method.");
    } else if (action == 1 && currentValues.size() != 0) {
        throw new HandleException(HandleException.HANDLE_ALREADY_EXISTS,
                "The pid " + pid + " already exists. Use the update method.");
    }//w  ww  .j  av  a2s. co  m

    // add non-PID webservice handles ( other than those managed here like URL, LID and the 10320/loc )
    preserveHandles(na, pid, currentValues, handles);
    final int timestamp = (int) (System.currentTimeMillis() / 1000);
    final BasicDBList _lookup = new BasicDBList();
    final BasicDBList list = new BasicDBList();
    for (Handle handle : handles) {
        handle.setTimestamp(timestamp);
        handle.setTTLType(HandleValue.TTL_TYPE_RELATIVE);
        handle.setTTL(86400);
        final BasicDBObject hv = handleStorage.setHandleValue(handle);
        list.add(hv);
        _lookup.addAll(handle.getLocations());
    }

    final BasicDBObject handle = new BasicDBObject("handle", pid);
    handle.put("handles", list);
    handle.put("_lookup", _lookup);
    final DBCollection collection = handleStorage.getCollection(Util.encodeString(pid));
    final WriteResult result = collection.update(query, handle, true, false); // Upsert
    if (result.getN() == 0)
        throw new HandleException(900, "Cannot create or update the pid " + pid);
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

protected WriteResult doUpdate(final String collectionName, final Query query, final Update update,
        final Class<?> entityClass, final boolean upsert, final boolean multi) {

    return execute(collectionName, new CollectionCallback<WriteResult>() {
        public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException {

            MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);

            increaseVersionForUpdateIfNecessary(entity, update);

            DBObject queryObj = query == null ? new BasicDBObject()
                    : queryMapper.getMappedObject(query.getQueryObject(), entity);
            DBObject updateObj = update == null ? new BasicDBObject()
                    : updateMapper.getMappedObject(update.getUpdateObject(), entity);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Calling update using query: {} and update: {} in collection: {}",
                        serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName);
            }/*from  ww w.  j a  va2  s.  com*/

            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName,
                    entityClass, updateObj, queryObj);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            WriteResult writeResult = writeConcernToUse == null
                    ? collection.update(queryObj, updateObj, upsert, multi)
                    : collection.update(queryObj, updateObj, upsert, multi, writeConcernToUse);

            if (entity != null && entity.hasVersionProperty() && !multi) {
                if (ReflectiveWriteResultInvoker.wasAcknowledged(writeResult) && writeResult.getN() == 0
                        && dbObjectContainsVersionProperty(queryObj, entity)) {
                    throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: "
                            + updateObj.toMap().toString() + " to collection " + collectionName);
                }
            }

            handleAnyWriteResultErrors(writeResult, queryObj, MongoActionOperation.UPDATE);
            return writeResult;
        }
    });
}

From source file:org.vertx.mods.MongoPersistor.java

License:Apache License

private void doUpdate(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;// w  w w  .  j  a  va 2 s. c  o m
    }
    JsonObject criteriaJson = getMandatoryObject("criteria", message);
    if (criteriaJson == null) {
        return;
    }
    DBObject criteria = jsonToDBObject(criteriaJson);

    JsonObject objNewJson = getMandatoryObject("objNew", message);
    if (objNewJson == null) {
        return;
    }
    DBObject objNew = jsonToDBObject(objNewJson);
    Boolean upsert = message.body.getBoolean("upsert", false);
    Boolean multi = message.body.getBoolean("multi", false);
    DBCollection coll = db.getCollection(collection);

    WriteResult res = coll.update(criteria, objNew, upsert, multi);
    if (res.getError() == null) {
        JsonObject reply = new JsonObject();
        sendOK(message, reply);
    } else {
        sendError(message, res.getError());
    }
}

From source file:rapture.sheet.mongodb.MongoMetaSheetStore.java

License:Open Source License

public RaptureSheetStyle putSheetStyle(String name, RaptureSheetStyle style) {
    style.setName(style.getName());/*from  w w  w.  ja  va 2s .com*/
    String content = JacksonUtil.jsonFromObject(style);
    BasicDBObject query = new BasicDBObject();
    query.append(TYPE, STYLE);
    query.append(KEY, name);
    query.append(NAME, style.getName());

    BasicDBObject write = new BasicDBObject();
    write.append(TYPE, STYLE);
    write.append(KEY, name);
    write.append(NAME, style.getName());
    write.append(VALUE, content);
    DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
    collection.update(query, write, true, false);
    return style;
}

From source file:rapture.sheet.mongodb.MongoMetaSheetStore.java

License:Open Source License

public RaptureSheetScript putSheetScript(String name, String scriptName, RaptureSheetScript script) {
    script.setName(scriptName);//w  w  w.  jav a  2  s  .  c o  m
    String content = JacksonUtil.jsonFromObject(script);
    BasicDBObject query = new BasicDBObject();
    query.append(TYPE, SCRIPT);
    query.append(KEY, name);
    query.append(NAME, scriptName);

    BasicDBObject write = new BasicDBObject();
    write.append(TYPE, SCRIPT);
    write.append(KEY, name);
    write.append(NAME, scriptName);
    write.append(VALUE, content);
    DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
    collection.update(query, write, true, false);
    return script;
}

From source file:rapture.sheet.mongodb.MongoMetaSheetStore.java

License:Open Source License

public RaptureSheetRange putSheetNamedSelection(String name, String rangeName, RaptureSheetRange range) {
    range.setName(rangeName);//from w  w  w .j a v  a2 s.  c o m
    String content = JacksonUtil.jsonFromObject(range);
    BasicDBObject query = new BasicDBObject();
    query.append(TYPE, RANGE);
    query.append(KEY, name);
    query.append(NAME, rangeName);

    BasicDBObject write = new BasicDBObject();
    write.append(TYPE, RANGE);
    write.append(KEY, name);
    write.append(NAME, rangeName);
    write.append(VALUE, content);
    DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
    collection.update(query, write, true, false);
    return range;
}

From source file:rapture.sheet.mongodb.MongoMetaSheetStore.java

License:Open Source License

public RaptureSheetNote putSheetNote(String name, RaptureSheetNote note) {
    if (note.getId() == null || note.getId().isEmpty()) {
        note.setId(IDGenerator.getUUID());
    }//from   ww w .  ja  va 2s  . c  o  m
    String content = JacksonUtil.jsonFromObject(note);
    BasicDBObject query = new BasicDBObject();
    query.append(TYPE, NOTE);
    query.append(KEY, name);
    query.append(NAME, note.getId());

    BasicDBObject write = new BasicDBObject();
    write.append(TYPE, NOTE);
    write.append(KEY, name);
    write.append(NAME, note.getId());
    write.append(VALUE, content);
    DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
    collection.update(query, write, true, false);
    return note;
}

From source file:rtpmt.models.Shock.java

public void save() {
    DBCollection packageColl = db.getCollection(DBConstants.SHOCK_COLLECTION);

    BasicDBObject query = new BasicDBObject();
    query.put(DBConstants.SENSOR_ID, this.get(DBConstants.SENSOR_ID));
    query.put(DBConstants.TRUCK_ID, this.get(DBConstants.TRUCK_ID));
    query.put(DBConstants.PACKAGE_ID, this.get(DBConstants.PACKAGE_ID));
    query.put(DBConstants.TIMESTAMP, this.get(DBConstants.TIMESTAMP));

    BasicDBObject set = new BasicDBObject();
    set.put("$set", this);
    packageColl.update(query, set, true, false);
    //packageColl.insert(this, WriteConcern.ACKNOWLEDGED);
}

From source file:rtpmt.models.Vibration.java

public void save() {
    DBCollection packageColl = db.getCollection(DBConstants.VIBRATION_COLLECTION);

    BasicDBObject query = new BasicDBObject();
    query.put(DBConstants.SENSOR_ID, this.get(DBConstants.SENSOR_ID));
    query.put(DBConstants.TRUCK_ID, this.get(DBConstants.TRUCK_ID));
    query.put(DBConstants.PACKAGE_ID, this.get(DBConstants.PACKAGE_ID));
    query.put(DBConstants.TIMESTAMP, this.get(DBConstants.TIMESTAMP));
    BasicDBObject set = new BasicDBObject();
    set.put("$set", this);
    packageColl.update(query, set, true, false);
    //packageColl.insert(this, WriteConcern.ACKNOWLEDGED);
}

From source file:usermanager.Main3.java

private void btnUpsertUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpsertUserActionPerformed
    // Get connection to the Collection
    DB userDB = DBManager.getDatabase();
    DBCollection col = userDB.getCollection("user");
    // Search/*w  w  w . j a  v  a  2 s.  com*/
    BasicDBObject query = new BasicDBObject();
    query.put("_id", Integer.parseInt(txtId.getText()));
    // Update values
    BasicDBObject doc = new BasicDBObject();
    doc.put("firstName", txtFirstName.getText());
    doc.put("lastName", txtLastName.getText());
    // Update object only with the relevant fields using $set
    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", doc);

    // Only difference is last two parameters
    /*Parameters:
    q - the selection criteria for the update
    o - the modifications to apply
    upsert - when true, inserts a document if no document matches the update query criteria
    multi - when true, updates all documents in the collection that 
       match the update query criteria, otherwise only updates one
    */
    WriteResult result = col.update(query, updateObj, true, false);
}