Example usage for com.mongodb.client MongoCollection findOneAndReplace

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

Introduction

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

Prototype

@Nullable
TDocument findOneAndReplace(Bson filter, TDocument replacement);

Source Link

Document

Atomically find a document and replace it.

Usage

From source file:org.jnosql.diana.mongodb.document.MongoDBDocumentCollectionManager.java

License:Open Source License

@Override
public DocumentEntity update(DocumentEntity entity) {
    DocumentEntity copy = entity.copy();
    String collectionName = entity.getName();
    MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
    Document id = copy.find(ID_FIELD).map(d -> new Document(d.getName(), d.getValue().get()))
            .orElseThrow(() -> new UnsupportedOperationException(
                    "To update this DocumentEntity " + "the field `id` is required"));
    copy.remove(ID_FIELD);/*  ww w  .  j av  a 2s.c om*/
    collection.findOneAndReplace(id, getDocument(entity));
    return entity;
}

From source file:Principal.ETL.ETLDAO.Mongo.java

public static void insertimage(Imagen img) {
    Document bson = null;//from ww  w  . jav a  2  s . c  o m

    try {

        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        bson = img.toBson();
        // Now connect to your databases
        MongoDatabase db = mongoClient.getDatabase("test");
        System.out.println("Connect to database successfully");

        MongoCollection coll = db.getCollection("imagenes");
        System.out.println("Collection mycol selected successfully");

        Document i = new Document().append("_id", bson.get("_id"));
        if (!coll.find(i).iterator().hasNext()) {
            coll.insertOne(bson);
        } else {
            coll.findOneAndReplace(i, bson);
        }

        //    FindIterable cursor = coll.find();
        //         MongoCursor x = cursor.iterator();      

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

}