Example usage for com.mongodb.client.model Updates currentDate

List of usage examples for com.mongodb.client.model Updates currentDate

Introduction

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

Prototype

public static Bson currentDate(final String fieldName) 

Source Link

Document

Creates an update that sets the value of the field to the current date as a BSON date.

Usage

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void storeBinaryData(byte[] data, String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    MongoCollection<Document> collection = db.getCollection(collectionName);
    Document doc = collection.find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1).first();

    if (data == null) {
        // We assume that if the value is set to null, we should delete also the corresponding database entry
        if (doc != null) {
            collection.deleteOne(Filters.eq(IDENTIFIER_FIELD, identifier));
        }//ww w .ja  v a 2s  .c  o  m
    } else {
        // Check if the document already exists and update it
        if (doc != null) {
            collection.updateOne(Filters.eq(IDENTIFIER_FIELD, identifier),
                    Updates.combine(Updates.set(DATA_FIELD, data), Updates.currentDate("lastModified")));
        } else {
            Document document = new Document(IDENTIFIER_FIELD, identifier).append(DATA_FIELD, data)
                    .append("lastModified", new Date());
            collection.insertOne(document);
        }
    }

    client.close();
}