Example usage for com.mongodb.client.model UpdateOptions UpdateOptions

List of usage examples for com.mongodb.client.model UpdateOptions UpdateOptions

Introduction

In this page you can find the example usage for com.mongodb.client.model UpdateOptions UpdateOptions.

Prototype

UpdateOptions

Source Link

Usage

From source file:com.bluedragon.mongo.MongoCollectionUpdate.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    String collection = getNamedStringParam(argStruct, "collection", null);
    if (collection == null)
        throwException(_session, "please specify a collection");

    cfData data = getNamedParam(argStruct, "data", null);
    if (data == null)
        throwException(_session, "please specify data to update");

    cfData query = getNamedParam(argStruct, "query", null);
    if (query == null)
        throwException(_session, "please specify query to update");

    boolean upsert = getNamedBooleanParam(argStruct, "upsert", false);
    boolean multi = getNamedBooleanParam(argStruct, "multi", false);

    try {/*from   www  . j  av a 2  s.  co m*/

        MongoCollection<Document> col = db.getCollection(collection);
        Document qry = getDocument(query);
        Document dat = getDocument(data);
        long start = System.currentTimeMillis();

        if (multi)
            col.updateMany(qry, dat, new UpdateOptions().upsert(upsert));
        else
            col.updateOne(qry, dat, new UpdateOptions().upsert(upsert));

        _session.getDebugRecorder().execMongo(col, "update", qry, System.currentTimeMillis() - start);

        return cfBooleanData.TRUE;

    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.dawsonsystems.session.MongoManager.java

License:Apache License

public void save(Session session) throws IOException {
    try {/*w  w w.  jav  a2  s.com*/
        log.fine("Saving session " + session + " into Mongo");

        StandardSession standardsession = (MongoSession) session;

        if (log.isLoggable(Level.FINE)) {
            log.fine("Session Contents [" + session.getId() + "]:");
            for (Object name : Collections.list(standardsession.getAttributeNames())) {
                log.fine("  " + name);
            }
        }

        byte[] data = serializer.serializeFrom(standardsession);

        BasicDBObject dbsession = new BasicDBObject();
        dbsession.put("_id", standardsession.getId());
        dbsession.put("data", data);
        if (localHostName != null) {
            dbsession.put("lasthost", localHostName);
        }
        dbsession.put("lastmodified", System.currentTimeMillis());

        Bson filter = eq("_id", standardsession.getIdInternal());
        getCollection().updateOne(filter, dbsession, new UpdateOptions().upsert(true));
        log.fine("Updated session with id " + session.getIdInternal());
    } catch (IOException e) {
        log.severe(e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        currentSession.remove();
        log.fine("Session removed from ThreadLocal :" + session.getIdInternal());
    }
}

From source file:com.dydabo.blackbox.mongodb.tasks.MongoInsertTask.java

License:Apache License

private Boolean upsertDocument(Document doc) {
    UpdateOptions uo = new UpdateOptions().upsert(true);
    getCollection().replaceOne(Filters.eq("_id", doc.get("_id")), doc, uo);
    return true;//from  w  ww  . j  a  v a2 s  . co  m
}

From source file:com.eightkdata.mongowp.client.wrapper.MongoConnectionWrapper.java

License:Open Source License

@Override
public void asyncUpdate(String database, String collection, BsonDocument selector, BsonDocument update,
        boolean upsert, boolean multiUpdate) throws MongoException {

    try {/*from w  w  w . j  ava2 s  .  c om*/
        UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);

        MongoCollection<org.bson.BsonDocument> mongoCollection = owner.getDriverClient().getDatabase(database)
                .getCollection(collection, org.bson.BsonDocument.class);
        org.bson.BsonDocument translatedUpdate = MongoBsonTranslator.translate(update);
        if (multiUpdate) {
            mongoCollection.updateMany(translatedUpdate, translatedUpdate, updateOptions);
        } else {
            mongoCollection.updateOne(translatedUpdate, translatedUpdate, updateOptions);
        }
    } catch (com.mongodb.MongoException ex) { //a general Mongo driver exception
        if (ErrorCode.isErrorCode(ex.getCode())) {
            throw toMongoException(ex);
        } else {
            throw toRuntimeMongoException(ex);
        }
    } catch (IOException ex) {
        throw new BadValueException("Unexpected IO exception", ex);
    }
}

From source file:com.epam.dlab.backendapi.dao.BaseDAO.java

License:Apache License

/**
 * Update or insert single document in the collection by condition.
 *
 * @param collection collection name./*from w  w w  . j  a va  2s .com*/
 * @param condition  condition for search documents in collection.
 * @param document   document.
 * @param isUpsert   if <b>true</b> document will be updated or inserted.
 */
protected void updateOne(String collection, Bson condition, Bson document, boolean isUpsert) {
    try {
        if (isUpsert) {
            mongoService.getCollection(collection).updateOne(condition, document,
                    new UpdateOptions().upsert(true));
        } else {
            mongoService.getCollection(collection).updateOne(condition, document);
        }
    } catch (MongoException e) {
        LOGGER.warn("Upsert Mongo DB fails: {}", e.getLocalizedMessage(), e);
        throw new DlabException("Upsert to Mongo DB fails: " + e.getLocalizedMessage(), e);
    }
}

From source file:com.epam.dlab.core.ModuleData.java

License:Apache License

public void store() {
    //TODO refactor this module move working with db to DAO layer
    final Document document = new Document().append(ID_FIELD, id).append(MODIFICATION_DATE, modificationDate)
            .append(ENTRIES_FIELD, entries);
    connection.getCollection(MongoConstants.BILLING_DATA_COLLECTION).updateOne(eq(ID_FIELD, id),
            new Document("$set", document), new UpdateOptions().upsert(true));
    modified = false;//from  w  w w . j  a v a  2  s . c  om
}

From source file:com.erudika.para.persistence.MongoDBDAO.java

License:Apache License

private String createRow(String key, String appid, Document row) {
    if (StringUtils.isBlank(key) || StringUtils.isBlank(appid) || row == null || row.isEmpty()) {
        return null;
    }/*w ww  .j  av  a  2s  .c  o m*/
    try {
        // if there isn't a document with the same id then create a new document
        // else replace the document with the same id with the new one
        getTable(appid).replaceOne(new Document(_ID, key), row, new UpdateOptions().upsert(true));
    } catch (Exception e) {
        logger.error(null, e);
    }
    return key;
}

From source file:com.exorath.exodata.impl.IExoDocument.java

License:Apache License

@Override
public Observable<UpdateResult> update(Bson query, Bson update, boolean upsert) {
    return Observable.create((subscriber -> {
        subscriber.onNext(collection.updateOne(query, update, new UpdateOptions().upsert(upsert)));
        subscriber.onCompleted();//from  www. j  av  a  2s .c o m
    })).subscribeOn(Schedulers.io()).cast(UpdateResult.class);
}

From source file:com.exorath.service.hideplayers.service.MongoService.java

License:Apache License

@Override
public Success setVisibilityPlayer(String uuid, VisibilityPlayer player) {
    try {//  ww w. java  2 s .  c  o m
        visibilityPlayersCollection.updateOne(new Document("_id", uuid),
                Updates.set("state", player.getState().toString()), new UpdateOptions().upsert(true));
        return new Success(true);
    } catch (Exception e) {
        e.printStackTrace();
        return new Success(false, -1, e.getMessage());
    }
}

From source file:com.github.cherimojava.data.mongo.entity.EntityInvocationHandler.java

License:Apache License

/**
 * stores the given EntityInvocationHandler represented Entity in the given Collection
 *
 * @param handler/*from  w  w  w .j  av a2s. c o  m*/
 *            EntityInvocationHandler (Entity) to save
 * @param coll
 *            MongoCollection to save entity into
 */
@SuppressWarnings("unchecked")
static <T extends Entity> void save(EntityInvocationHandler handler, MongoCollection<T> coll) {
    for (ParameterProperty cpp : handler.properties.getValidationProperties()) {
        cpp.validate(handler.data.get(cpp.getMongoName()));
    }
    BsonDocumentWrapper wrapper = new BsonDocumentWrapper<>(handler.proxy,
            (org.bson.codecs.Encoder<Entity>) coll.getCodecRegistry().get(handler.properties.getEntityClass()));
    UpdateResult res = coll.updateOne(
            new BsonDocument("_id",
                    BsonDocumentWrapper.asBsonDocument(EntityCodec._obtainId(handler.proxy), idRegistry)),
            new BsonDocument("$set", wrapper), new UpdateOptions());
    if (res.getMatchedCount() == 0) {
        // TODO this seems too nasty, there must be a better way.for now live with it
        coll.insertOne((T) handler.proxy);
    }
    handler.persist();
}