Example usage for com.mongodb.client MongoCollection replaceOne

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

Introduction

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

Prototype

UpdateResult replaceOne(ClientSession clientSession, Bson filter, TDocument replacement);

Source Link

Document

Replace a document in the collection according to the specified arguments.

Usage

From source file:org.apache.nifi.processors.mongodb.PutMongo.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;// ww w.  java  2 s  .  co m
    }

    final ComponentLog logger = getLogger();

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String mode = context.getProperty(MODE).getValue();
    final String updateMode = context.getProperty(UPDATE_MODE).getValue();
    final WriteConcern writeConcern = getWriteConcern(context);

    final MongoCollection<Document> collection = getCollection(context, flowFile)
            .withWriteConcern(writeConcern);

    try {
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, in -> StreamUtils.fillBuffer(in, content, true));

        // parse
        final Object doc = (mode.equals(MODE_INSERT)
                || (mode.equals(MODE_UPDATE) && updateMode.equals(UPDATE_WITH_DOC.getValue())))
                        ? Document.parse(new String(content, charset))
                        : JSON.parse(new String(content, charset));

        if (MODE_INSERT.equalsIgnoreCase(mode)) {
            collection.insertOne((Document) doc);
            logger.info("inserted {} into MongoDB", new Object[] { flowFile });
        } else {
            // update
            final boolean upsert = context.getProperty(UPSERT).asBoolean();
            final String updateKey = context.getProperty(UPDATE_QUERY_KEY).getValue();

            Object keyVal = ((Map) doc).get(updateKey);
            if (updateKey.equals("_id") && ObjectId.isValid(((String) keyVal))) {
                keyVal = new ObjectId((String) keyVal);
            }

            final Document query = new Document(updateKey, keyVal);

            if (updateMode.equals(UPDATE_WITH_DOC.getValue())) {
                collection.replaceOne(query, (Document) doc, new UpdateOptions().upsert(upsert));
            } else {
                BasicDBObject update = (BasicDBObject) doc;
                update.remove(updateKey);
                collection.updateOne(query, update, new UpdateOptions().upsert(upsert));
            }
            logger.info("updated {} into MongoDB", new Object[] { flowFile });
        }

        session.getProvenanceReporter().send(flowFile, getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        logger.error("Failed to insert {} into MongoDB due to {}", new Object[] { flowFile, e }, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}

From source file:org.flinkmon.source.MongoDBOplogSource.java

License:Open Source License

private void updateHostOperationTimeStamp(MongoCollection<Document> tsCollection, BsonTimestamp lastTimeStamp,
        String host) {//from  w  w  w . j  av a 2  s. co  m
    try {
        tsCollection.replaceOne(new Document("_id", host),
                new Document("_id", host).append(OPLOG_TIMESTAMP, lastTimeStamp),
                (new UpdateOptions()).upsert(true));
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

From source file:org.radarcns.connect.mongodb.MongoWrapper.java

License:Apache License

/**
 * Store a document in MongoDB. If the document has an ID, it will replace existing
 * documents with that ID. If it does not, it will be inserted and MongoDB will assign it with
 * a unique ID.// w  ww .  ja va2 s.c  o  m
 *
 * @param topic Kafka topic that the document belongs to
 * @param doc MongoDB document
 * @throws MongoException if the document could not be stored.
 */
public void store(String topic, Document doc) throws MongoException {
    MongoCollection<Document> collection = getCollection(topic);
    Object mongoId = doc.get(MONGO_ID_KEY);
    if (mongoId != null) {
        collection.replaceOne(eq(MONGO_ID_KEY, mongoId), doc, UPDATE_UPSERT);
    } else {
        collection.insertOne(doc);
    }
}

From source file:org.radarcns.mongodb.MongoWrapper.java

License:Apache License

/**
 * Store a document in MongoDB/*  w w w  .  j a va2 s . com*/
 * @param topic Kafka topic that the document belongs to
 * @param doc MongoDB document
 * @throws MongoException if the document could not be stored
 */
public void store(String topic, Document doc) throws MongoException {
    MongoDatabase database = mongoClient.getDatabase(dbName);
    String collectionName = collectionFormat.replace("{$topic}", topic);
    MongoCollection<Document> collection = database.getCollection(collectionName);

    collection.replaceOne(eq("_id", doc.get("_id")), doc, (new UpdateOptions()).upsert(true));
}

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

License:Open Source License

public static boolean restoreDocument(MongoCollection<BsonDocument> coll, Object documentId,
        BsonDocument shardKeys, BsonDocument data, Object etag) {
    Objects.requireNonNull(coll);
    Objects.requireNonNull(documentId);
    Objects.requireNonNull(data);

    Bson query;/*from ww  w.  j  av  a 2 s.co m*/

    if (etag == null) {
        query = eq("_id", documentId);
    } else {
        query = and(eq("_id", documentId), eq("_etag", etag));
    }

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

    UpdateResult result = coll.replaceOne(query, data, U_NOT_UPSERT_OPS);

    if (result.isModifiedCountAvailable()) {
        return result.getModifiedCount() == 1;
    } else {
        return true;
    }
}

From source file:rocks.devonthe.stickychunk.database.MongodbDatabase.java

License:GNU General Public License

public void saveRegionData(LoadedRegion loadedRegion) {
    MongoCollection<Document> collection = getDatabase().getCollection("chunks");

    Document regionDocument = new Document("_id", loadedRegion.getUniqueId().toString())
            .append("owner", loadedRegion.getOwner().toString())
            .append("world", loadedRegion.getWorld().getUniqueId().toString())
            .append("type", loadedRegion.getType().toString())
            .append("fromX", loadedRegion.getRegion().getFrom().getX())
            .append("fromZ", loadedRegion.getRegion().getFrom().getZ())
            .append("toX", loadedRegion.getRegion().getTo().getX())
            .append("toZ", loadedRegion.getRegion().getTo().getZ()).append("created", loadedRegion.getEpoch());

    collection.replaceOne(Filters.eq("_id", loadedRegion.getUniqueId().toString()), regionDocument,
            (new UpdateOptions()).upsert(true));
}

From source file:rocks.devonthe.stickychunk.database.MongodbDatabase.java

License:GNU General Public License

public void saveUserData(UserData userData) {
    MongoCollection<Document> collection = getDatabase().getCollection("users");

    Document userDocument = new Document("_id", userData.getUniqueId()).append("seen", userData.getLastSeen())
            .append("joined", userData.getUserJoined());

    collection.replaceOne(Filters.eq("_id", userData.getUniqueId().toString()), userDocument,
            (new UpdateOptions()).upsert(true));
}