Example usage for com.mongodb.client MongoCollection updateOne

List of usage examples for com.mongodb.client MongoCollection updateOne

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection updateOne.

Prototype

UpdateResult updateOne(ClientSession clientSession, Bson filter, List<? extends Bson> update);

Source Link

Document

Update a single document in the collection according to the specified arguments.

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 {/*ww w. ja  va2s .  c o 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.eclipsesource.connect.persistence.MongoStorage.java

License:Open Source License

@Override
public void store(String place, Object object, Object... objects) {
    validateArguments(place, object);/*w  w  w.  ja  v  a2  s.  c  o  m*/
    MongoDatabase db = factory.getDB();
    MongoCollection<Document> collection = db.getCollection(place);
    List<Document> documents = createDocuments(object, objects);
    documents.forEach(document -> {
        collection.updateOne(eq(KEY_ID, document.get(KEY_ID)), new Document("$set", document), UPDATE_OPTIONS);
    });
    notifyObservers(place, object, objects);
}

From source file:com.eclipsesource.connect.test.util.persistence.InMemoryStorage.java

License:Open Source License

@Override
public void store(String place, Object object, Object... objects) {
    validateArguments(place, object);/*from  w w w  . j a  va  2  s . com*/
    MongoCollection<Document> collection = db.getCollection(place);
    List<Document> documents = createDocuments(object, objects);
    documents.forEach(document -> {
        collection.updateOne(eq(KEY_ID, document.get(KEY_ID)), new Document("$set", document), UPDATE_OPTIONS);
    });
}

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  ww. java 2 s.  c  o m
        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.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 . java 2 s  .  com
 *            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();
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Inserts a new document with given resolution in the given aggregated collection within the given database
 * (row-like mode)./*  w  w w .j  a  v  a2  s .  c  o m*/
 * @param dbName
 * @param collectionName
 * @param recvTimeTs
 * @param entityId
 * @param entityType
 * @param attrName
 * @param attrType
 * @param attrValue
 * @param resolution
 */
private void insertContextDataAggregatedForResoultion(String dbName, String collectionName,
        GregorianCalendar calendar, String entityId, String entityType, String attrName, String attrType,
        double attrValue, Resolution resolution) {
    // get database and collection
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);

    // build the query
    BasicDBObject query = buildQueryForInsertAggregated(calendar, entityId, entityType, attrName, resolution);

    // prepopulate if needed
    BasicDBObject insert = buildInsertForPrepopulate(attrType, resolution);
    UpdateResult res = collection.updateOne(query, insert, new UpdateOptions().upsert(true));

    if (res.getMatchedCount() == 0) {
        LOGGER.debug("Prepopulating data, database=" + dbName + ", collection=" + collectionName + ", query="
                + query.toString() + ", insert=" + insert.toString());
    } // if

    // do the update
    BasicDBObject update = buildUpdateForUpdate(attrType, attrValue);
    LOGGER.debug("Updating data, database=" + dbName + ", collection=" + collectionName + ", query="
            + query.toString() + ", update=" + update.toString());
    collection.updateOne(query, update);
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Stores in per-service/database "collection_names" collection the matching between a hash and the fields used to
 * build it./*  w w  w. j  a  v a 2  s .  c o  m*/
 * FIXME: destination is under study
 * @param dbName
 * @param hash
 * @param isAggregated
 * @param fiwareService
 * @param fiwareServicePath
 * @param entityId
 * @param entityType
 * @param attrName
 * @param destination
 * @throws java.lang.Exception
 */
public void storeCollectionHash(String dbName, String hash, boolean isAggregated, String fiwareService,
        String fiwareServicePath, String entityId, String entityType, String attrName, String destination)
        throws Exception {
    // get the database and the collection; the collection is created if not existing
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection;

    try {
        LOGGER.debug("Creating Mongo collection=collection_names at database=" + dbName);
        db.createCollection("collection_names");
    } catch (Exception e) {
        if (e.getMessage().contains("collection already exists")) {
            LOGGER.debug("Collection already exists, nothing to create");
        } else {
            throw e;
        } // if else
    } finally {
        collection = db.getCollection("collection_names");
    } // try catch finally

    // Two updates operations are needed since MongoDB currently does not support the possibility to address the
    // same field in a $set operation as a $setOnInsert operation. More details:
    // http://stackoverflow.com/questions/23992723/ \
    //     findandmodify-fails-with-error-cannot-update-field1-and-field1-at-the-same

    // build the query
    BasicDBObject query = new BasicDBObject().append("_id", hash + (isAggregated ? ".aggr" : ""));

    // do the first update
    BasicDBObject update = buildUpdateForCollectionHash("$setOnInsert", isAggregated, fiwareService,
            fiwareServicePath, entityId, entityType, attrName, destination);
    LOGGER.debug("Updating data, database=" + dbName + ", collection=collection_names, query="
            + query.toString() + ", update=" + update.toString());
    UpdateResult res = collection.updateOne(query, update, new UpdateOptions().upsert(true));
    /*
            TECHDEBT:
            https://github.com/telefonicaid/fiware-cygnus/issues/428
            https://github.com/telefonicaid/fiware-cygnus/issues/429
                    
            if (res.getMatchedCount() == 0) {
    LOGGER.error("There was an error when storing the collecion hash, database=" + dbName
            + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString());
    return;
            } // if
                    
            // do the second update
            update = buildUpdateForCollectionHash("$set", isAggregated, fiwareService, fiwareServicePath, entityId,
        entityType, attrName, destination);
            LOGGER.debug("Updating data, database=" + dbName + ", collection=collection_names, query="
        + query.toString() + ", update=" + update.toString());
            res = collection.updateOne(query, update);
                    
            if (res.getMatchedCount() == 0) {
    LOGGER.error("There was an error when storing the collecion hash, database=" + dbName
            + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString());
            } // if
    */
}

From source file:com.threecrickets.prudence.cache.HazelcastMongoDbMapStore.java

License:LGPL

public void store(K key, V value) {
    MongoCollection<Document> collection = getCollection();
    Document query = new Document();
    Document update = new Document();
    Document set = new Document();

    query.put("_id", key);
    update.put("$set", set);
    set.put("value", toBinary(value));

    collection.updateOne(query, update, new UpdateOptions().upsert(true));
}

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

License:Apache License

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

    try {//from ww  w.  ja  v  a 2  s.c  o  m
        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);
        }
    }
}

From source file:documentation.CausalConsistencyExamples.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *//*from w ww. j  a v a  2 s  .c om*/
public static void main(final String[] args) {
    setupDatabase();
    MongoClient client = MongoClients.create();

    // Start Causal Consistency Example 1
    // Example 1: Use a causally consistent session to ensure that the update occurs before the insert.
    ClientSession session1 = client
            .startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
    Date currentDate = new Date();
    MongoCollection<Document> items = client.getDatabase("test").withReadConcern(ReadConcern.MAJORITY)
            .withWriteConcern(WriteConcern.MAJORITY.withWTimeout(1000, TimeUnit.MILLISECONDS))
            .getCollection("test");

    items.updateOne(session1, eq("sku", "111"), set("end", currentDate));

    Document document = new Document("sku", "nuts-111").append("name", "Pecans").append("start", currentDate);
    items.insertOne(session1, document);
    // End Causal Consistency Example 1

    // Start Causal Consistency Example 2
    // Example 2: Advance the cluster time and the operation time to that of the other session to ensure that
    // this client is causally consistent with the other session and read after the two writes.
    ClientSession session2 = client
            .startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
    session2.advanceClusterTime(session1.getClusterTime());
    session2.advanceOperationTime(session1.getOperationTime());

    items = client.getDatabase("test").withReadPreference(ReadPreference.secondary())
            .withReadConcern(ReadConcern.MAJORITY)
            .withWriteConcern(WriteConcern.MAJORITY.withWTimeout(1000, TimeUnit.MILLISECONDS))
            .getCollection("items");

    for (Document item : items.find(session2, eq("end", BsonNull.VALUE))) {
        System.out.println(item);
    }
    // End Causal Consistency Example 2
}