Example usage for com.mongodb.client MongoCollection findOneAndUpdate

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

Introduction

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

Prototype

@Nullable
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, List<? extends Bson> update);

Source Link

Document

Atomically find a document and update it.

Usage

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

License:Open Source License

@SuppressWarnings("rawtypes")
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 update = getNamedParam(argStruct, "update", null);
    if (update == null)
        throwException(_session, "please specify update");

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

    try {/*  w w w  .  j  a v a  2  s. co m*/

        MongoCollection<Document> col = db.getCollection(collection);
        FindOneAndUpdateOptions findOneAndUpdateOptions = new FindOneAndUpdateOptions();

        if (getNamedParam(argStruct, "fields", null) != null)
            findOneAndUpdateOptions.projection(getDocument(getNamedParam(argStruct, "fields", null)));

        if (getNamedParam(argStruct, "sort", null) != null)
            findOneAndUpdateOptions.sort(getDocument(getNamedParam(argStruct, "sort", null)));

        findOneAndUpdateOptions.upsert(getNamedBooleanParam(argStruct, "upsert", false));

        if (getNamedBooleanParam(argStruct, "returnnew", false))
            findOneAndUpdateOptions.returnDocument(ReturnDocument.AFTER);

        Document qry = getDocument(query);
        long start = System.currentTimeMillis();

        Document result = col.findOneAndUpdate(qry, getDocument(update), findOneAndUpdateOptions);

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

        return tagUtils.convertToCfData((Map) result);

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

From source file:org.restheart.db.DAOUtils.java

License:Open Source License

/**
 *
 * @param coll/*w w w . j a  va  2s  .co m*/
 * @param documentId use Optional.empty() to specify no documentId (null is
 * _id: null)
 * @param shardKeys
 * @param data
 * @param replace
 * @param returnNew
 * @return the new or old document depending on returnNew
 */
public static OperationResult updateDocument(MongoCollection<BsonDocument> coll, Object documentId,
        BsonDocument shardKeys, BsonDocument data, boolean replace, boolean returnNew) {
    Objects.requireNonNull(coll);
    Objects.requireNonNull(data);

    BsonDocument document = getUpdateDocument(data);

    Bson query;

    boolean idPresent = true;

    if (documentId instanceof Optional && !((Optional) documentId).isPresent()) {
        query = IMPOSSIBLE_CONDITION;
        idPresent = false;
    } else {
        query = eq("_id", documentId);
    }

    if (shardKeys != null) {
        query = and(query, shardKeys);
    }

    if (replace) {
        // here we cannot use the atomic findOneAndReplace because it does
        // not support update operators.

        BsonDocument oldDocument;

        if (idPresent) {
            oldDocument = coll.findOneAndDelete(query);
        } else {
            oldDocument = null;
        }

        BsonDocument newDocument = coll.findOneAndUpdate(query, document, FAU_AFTER_UPSERT_OPS);

        return new OperationResult(-1, oldDocument, newDocument);
    } else if (returnNew) {
        BsonDocument newDocument = coll.findOneAndUpdate(query, document, FAU_AFTER_UPSERT_OPS);

        return new OperationResult(-1, null, newDocument);
    } else {
        BsonDocument oldDocument = coll.findOneAndUpdate(query, document, FAU_UPSERT_OPS);

        return new OperationResult(-1, oldDocument, null);
    }
}

From source file:org.restheart.plugins.services.CsvLoader.java

License:Open Source License

@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.isOptions()) {
        handleOptions(exchange, context);
    } else {/*from  w  w  w . j av a 2 s . co  m*/
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, Resource.JSON_MEDIA_TYPE);
        if (doesApply(context)) {
            if (checkContentType(exchange)) {
                try {
                    CsvRequestParams params = new CsvRequestParams(exchange);

                    try {
                        List<BsonDocument> documents = parseCsv(exchange, params, context,
                                context.getRawContent());

                        if (documents != null && documents.size() > 0) {
                            MongoCollection<BsonDocument> mcoll = MongoDBClientSingleton.getInstance()
                                    .getClient().getDatabase(params.db)
                                    .getCollection(params.coll, BsonDocument.class);

                            if (params.update) {
                                documents.stream().forEach(document -> {
                                    BsonDocument updateQuery = new BsonDocument("_id", document.remove("_id"));

                                    // for upate import, take _filter property into account
                                    // for instance, a filter allows to use $ positional array operator
                                    BsonValue _filter = document.remove(FILTER_PROPERTY);

                                    if (_filter != null && _filter.isDocument()) {
                                        updateQuery.putAll(_filter.asDocument());
                                    }
                                    if (params.upsert) {
                                        mcoll.findOneAndUpdate(updateQuery, new BsonDocument("$set", document),
                                                FAU_WITH_UPSERT_OPS);
                                    } else {

                                        mcoll.findOneAndUpdate(updateQuery, new BsonDocument("$set", document),
                                                FAU_NO_UPSERT_OPS);
                                    }
                                });
                            } else if (params.upsert) {
                                documents.stream().forEach(document -> {
                                    BsonDocument updateQuery = new BsonDocument("_id", document.remove("_id"));

                                    mcoll.findOneAndUpdate(updateQuery, new BsonDocument("$set", document),
                                            FAU_WITH_UPSERT_OPS);
                                });
                            } else {
                                mcoll.insertMany(documents);
                            }
                            context.setResponseStatusCode(HttpStatus.SC_OK);
                        } else {
                            context.setResponseStatusCode(HttpStatus.SC_NOT_MODIFIED);
                        }
                    } catch (IOException ex) {
                        LOGGER.debug("error parsing CSV data", ex);
                        ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST,
                                ERROR_PARSING_DATA);

                    }
                } catch (IllegalArgumentException iae) {
                    ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST,
                            ERROR_QPARAM);
                }
            } else {
                ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST,
                        ERROR_CONTENT_TYPE);
            }

        } else {
            ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_NOT_IMPLEMENTED,
                    ERROR_WRONG_METHOD);
        }
    }
    // this clean the error message about the wrong media type
    // added by BodyInjectorHandler
    context.setResponseContent(null);

    next(exchange, context);
}

From source file:rapture.mongodb.EpochManager.java

License:Open Source License

/**
 * Returns the next epoch available and advances the counter. Guaranteed to
 * be unique for the given collection. If the epoch document does not
 * already exist a new one is created and the first epoch returned will be
 * 1L./*  ww w. j  a  v  a  2 s.  co  m*/
 * 
 * @param collection
 *            - the MongoCollection to the get next epoch for
 * @return Long - a unique epoch value for this collection
 */
public static Long nextEpoch(final MongoCollection<Document> collection) {
    final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true)
            .returnDocument(ReturnDocument.AFTER);

    MongoRetryWrapper<Long> wrapper = new MongoRetryWrapper<Long>() {
        public Long action(FindIterable<Document> cursor) {
            Document ret = collection.findOneAndUpdate(getEpochQueryObject(),
                    getIncUpdateObject(getUpdateObject()), options);
            return (Long) ret.get(SEQ);
        }
    };
    return wrapper.doAction();
}

From source file:rapture.repo.mongodb.MongoDbDataStore.java

License:Open Source License

@Override
public void put(String key, String value) {
    MongoCollection<Document> collection = getCollection();
    Document query = new Document(KEY, key);
    Document toPut = new Document($SET, new Document(KEY, key).append(VALUE, value));

    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true)
            .returnDocument(ReturnDocument.BEFORE);
    Document result = collection.findOneAndUpdate(query, toPut, options);

    if (needsFolderHandling && result == null) {
        dirRepo.registerParentage(key);/*from w w w. ja va2 s .co  m*/
    }
}

From source file:rapture.series.mongo.MongoSeriesStore.java

License:Open Source License

private void saveDocument(String key, String column, Object val) {
    registerKey(key);//from   w  ww. j a  v  a  2  s .  c o  m
    MongoCollection<Document> collection = getCollection(key);
    Document dbkey = new Document(ROWKEY, key).append(COLKEY, column);
    Document dbval = new Document($SET, new Document(ROWKEY, key).append(COLKEY, column).append(VALKEY, val));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true)
            .returnDocument(ReturnDocument.AFTER);
    try {
        @SuppressWarnings("unused")
        Document ret = collection.findOneAndUpdate(dbkey, dbval, options);
    } catch (MongoException me) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, new ExceptionToString(me));
    }
}

From source file:rapture.table.mongodb.MongoIndexHandler.java

License:Open Source License

@Override
public void updateRow(String rowId, Map<String, Object> recordValues) {
    String key = getKey(rowId); // stupid key is row id plus "l/" prepended
                                // to it

    MongoCollection<Document> collection = MongoDBFactory.getCollection(instanceName, tableName);
    Document query = new Document();
    query.put(KEY, key);//from w  w w.  ja  va 2 s .  c o m
    Document toPut = new Document();
    toPut.put(KEY, key);
    toPut.put(ROWID, rowId);
    toPut.put(EPOCH, EpochManager.nextEpoch(collection));
    toPut.putAll(recordValues);

    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true)
            .returnDocument(ReturnDocument.AFTER);

    @SuppressWarnings("unused")
    Document ret = collection.findOneAndUpdate(query, new Document($SET, toPut), options);
}