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(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.imaginea.mongodb.services.impl.DocumentServiceImpl.java

License:Apache License

/**
 * Updates a document inside a collection in a database in mongo to which user is connected to.
 *
 * @param dbName Name of Database/*from w  ww . j a v a  2 s  .c om*/
 * @param collectionName Name of Collection from which to get all Documents
 * @param _id Id of Document to be updated
 * @param newData new Document value.
 * @return Update status
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException ,EmptyDocumentDataException
 * @throws CollectionException throw super type of UndefinedCollectionException
 * @throws DocumentException throw super type of UpdateDocumentException
 */

public String updateDocument(String dbName, String collectionName, String _id, Document newData)
        throws DatabaseException, CollectionException, DocumentException, ValidationException {

    if (dbName == null) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null");

    }
    if (dbName.equals("")) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty");
    }

    if (collectionName == null) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name is null");
    }
    if (collectionName.equals("")) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection Name Empty");
    }
    String result = null;

    try {
        // if (!databaseService.getDbList().contains(dbName)) {
        //   throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS,
        //       "DB [" + dbName + "] DOES NOT EXIST");
        // }

        if (!collectionService.getCollList(dbName).contains(collectionName)) {
            throw new CollectionException(ErrorCodes.COLLECTION_DOES_NOT_EXIST,
                    "COLLECTION [ " + collectionName + "] _DOES_NOT_EXIST in Db [ " + dbName + "]");
        }
        if (_id == null) {
            throw new DocumentException(ErrorCodes.DOCUMENT_EMPTY, "Document is empty");
        }

        String newId = (String) newData.get("_id");

        if (newId == null) {
            throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "Object Id is invalid.");
        }
        if (newId.equals("")) {
            throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "Object Id is invalid.");
        }

        ObjectId docId = new ObjectId(_id);

        if (!newId.equals(_id)) {
            throw new DocumentException(ErrorCodes.UPDATE_OBJECT_ID_EXCEPTION, "_id cannot be updated.");
        }

        MongoCollection<Document> collection = mongoInstance.getDatabase(dbName).getCollection(collectionName);

        Document document = collection.find(Filters.eq("_id", docId)).first();

        if (document != null) {

            ObjectId objectId = document.getObjectId("_id");

            newData.put("_id", objectId);

            Document updateData = new Document("$set", newData);
            collection.updateOne(Filters.eq("_id", objectId), updateData);

        } else {
            throw new DocumentException(ErrorCodes.DOCUMENT_DOES_NOT_EXIST, "Document does not exist !");
        }

    } catch (IllegalArgumentException e) {
        // When error converting object Id

        throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "Object Id is invalid.");

    } catch (MongoException e) {
        throw new DocumentException(ErrorCodes.DOCUMENT_UPDATE_EXCEPTION, e.getMessage());
    }
    result = "Document: [" + newData + "] has been updated.";

    return result;
}

From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java

License:Open Source License

/**
 * Updates an existing tweet with its sentiment information. <br>
 * @param id The id of the tweet to be updated
 * @param sentiment An integer representing the sentiment polarity of the tweet.
 * @param fieldName The name of the field where the sentiment will be stored.
 *//*  ww  w . ja  v  a  2s .c  om*/
public final void updateSentiment(long id, int sentiment, String fieldName) {
    MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName());
    try {
        collection.updateOne(new Document(config.getTweetIdFieldName(), id),
                new Document("$set", new Document(fieldName, sentiment)));
    } catch (NullPointerException e) {
        Utilities.printMessageln("There is no tweet with id '" + id + "'.");
        Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java

License:Open Source License

/**
 * Updates an existing tweet with emoticon information. <br>
 * More formally, the method adds two new attributes namely 'posEmot' and
 * 'negEmot' that indicate whether or not a given tweet has any positive or
 * negative emoticon, with zero indicating total absence and one indicating
 * at least one of each kind.//from   ww w  .  j a  v a2 s  .  co m
 * @param id The id of the tweet to be updated
 * @param positiveEmoticon An integer representing whether the tweet has any
 * positive emoticon in its text.
 * @param negativeEmoticon An integer representing whether the tweet has any
 * negative emoticon in its text.
 */
public final void updateTweetWithEmoticonInfo(long id, int positiveEmoticon, int negativeEmoticon) {
    MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName());
    try {
        collection.updateOne(new Document(config.getTweetIdFieldName(), id),
                new Document("$set", new Document(config.getPositiveEmoticonFieldName(), positiveEmoticon)));
        collection.updateOne(new Document(config.getTweetIdFieldName(), id),
                new Document("$set", new Document(config.getNegativeEmoticonFieldName(), negativeEmoticon)));
    } catch (NullPointerException e) {
        Utilities.printMessageln("There is no tweet with id '" + id + "'.");
        Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:com.navercorp.pinpoint.plugin.mongodb.MongoDBBase.java

License:Apache License

public void updateData(PluginTestVerifier verifier, MongoCollection<Document> collection,
        Class<?> mongoDatabaseImpl) {

    //update Data
    Document doc = new Document("name", "Roy").append("company", "Naver");
    Document doc2 = new Document("$set", new Document("name", "Roy3"));
    collection.updateOne(doc, doc2);

    Object[] objects = new Object[2];
    objects[0] = doc;// ww w  .j  a v a  2  s .  co  m
    objects[1] = doc2;

    StringStringValue parsedBson = MongoUtil.parseBson(objects, true);

    Method updateOne;
    try {
        updateOne = mongoDatabaseImpl.getDeclaredMethod("updateOne", Bson.class, Bson.class);
    } catch (NoSuchMethodException e) {
        updateOne = null;
    }

    verifier.verifyTrace(event(MONGO_EXECUTE_QUERY, updateOne, null, MONGODB_ADDRESS, null,
            new ExpectedAnnotation(MongoConstants.MONGO_COLLECTION_INFO.getName(), "customers"),
            new ExpectedAnnotation(MongoConstants.MONGO_COLLECTION_OPTION.getName(), "MAJORITY"),
            new ExpectedAnnotation(MongoConstants.MONGO_JSON_DATA.getName(), parsedBson)));
}

From source file:com.spleefleague.bungee.io.EntityBuilder.java

public static <T extends DBEntity & DBSaveable> void save(T object, MongoCollection<Document> dbcoll,
        boolean override) {
    DBEntity dbe = (DBEntity) object;//  ww w  . j  ava  2 s . c om
    ObjectId _id = dbe.getObjectId();
    Document index = null;
    if (override && _id != null) {
        index = new Document("_id", _id);
    }
    Document dbo = serialize(object);
    validate(dbo);
    if (index != null) {
        dbcoll.updateOne(index, dbo);
    } else {
        dbo = (Document) dbo.get("$set");
        dbcoll.insertOne(dbo);
        _id = (ObjectId) dbcoll.find(dbo).first().get("_id");
        try {
            Field _idField = DBEntity.class.getDeclaredField("_id");
            _idField.setAccessible(true);
            _idField.set(dbe, _id);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.spleefleague.core.io.EntityBuilder.java

public static <T extends DBEntity & DBSaveable> void save(T object, MongoCollection<Document> dbcoll,
        boolean override) {
    if (object == null) {
        return;/*  ww  w.  j a  va2s  .  c  o m*/
    }
    DBEntity dbe = (DBEntity) object;
    ObjectId _id = dbe.getObjectId();
    Document index = null;
    if (override && _id != null) {
        index = new Document("_id", _id);
    }
    Document dbo = serialize(object);
    validate(dbo);
    if (index != null) {
        dbcoll.updateOne(index, dbo);
    } else {
        dbo = (Document) dbo.get("$set");
        dbcoll.insertOne(dbo);
        _id = (ObjectId) dbcoll.find(dbo).first().get("_id");
        try {
            Field _idField = DBEntity.class.getDeclaredField("_id");
            _idField.setAccessible(true);
            _idField.set(dbe, _id);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.spleefleague.core.utils.DatabaseConnection.java

public static void updateFields(final MongoCollection<Document> dbcoll, final Document index,
        final Document update) {
    Bukkit.getScheduler().runTaskAsynchronously(SpleefLeague.getInstance(), () -> {
        dbcoll.updateOne(index, new Document("$set", update));
    });//from w  w  w  .  j  av a 2  s .co  m
}

From source file:com.yahoo.ycsb.db3.MongoDbClient.java

License:Open Source License

/**
 * Update a record in the database. Any field/value pairs in the specified
 * values HashMap will be written into the record with the specified record
 * key, overwriting any existing values with the same field name.
 * /*from   ww  w . j  a v a2s  .  c om*/
 * @param table
 *          The name of the table
 * @param key
 *          The record key of the record to write.
 * @param values
 *          A HashMap of field/value pairs to update in the record
 * @return Zero on success, a non-zero error code on error. See this class's
 *         description for a discussion of error codes.
 */
@Override
public Status update(String table, String key, HashMap<String, ByteIterator> values) {
    try {
        MongoCollection<Document> collection = database.getCollection(table);

        Document query = new Document("_id", key);
        Document fieldsToSet = new Document();
        for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
            fieldsToSet.put(entry.getKey(), entry.getValue().toArray());
        }
        Document update = new Document("$set", fieldsToSet);

        UpdateResult result = collection.updateOne(query, update);
        if (result.wasAcknowledged() && result.getMatchedCount() == 0) {
            System.err.println("Nothing updated for key " + key);
            return Status.NOT_FOUND;
        }
        return Status.OK;
    } catch (Exception e) {
        System.err.println(e.toString());
        return Status.ERROR;
    }
}

From source file:Controlador.Controlador.java

private void control() {
    ActionListener actionListener = new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
            //SORTIR
            if (actionEvent.getSource().equals(vista.getjButton6())) {
                System.out.println("Sortint... ADEU!");
                System.exit(0);/*www .  j  a va  2s . c om*/
            }
            //SORTIR DB
            if (actionEvent.getSource().equals(vistaDB.getjButton2())) {
                System.out.println("Sortint... ADEU!");
                System.exit(0);
            }
            //Carrega Coleccions DB
            if (actionEvent.getSource().equals(vistaDB.getjButton1())) {
                carregarColections();
                vistaDB.setVisible(false);
                vista.setVisible(true);
            }
            //Actualitzar document
            if (actionEvent.getSource().equals(vista.getjButton2())) {

                Document d = Document.parse(vista.getjTextArea1().getText());
                System.out.println(d);

                try {
                    MongoCollection col = model.getDatabase()
                            .getCollection(vista.getjList1().getSelectedValue());
                    //UpdateResult resultat = col.updateOne(eq("i", 10), set("i", 110));

                } catch (Exception e) {
                }

            }
            //Inserir documents sencers
            if (actionEvent.getSource().equals(vista.getjButton1())) {

                MongoCollection col = model.getMongoClient().getDatabase(vistaDB.getjList1().getSelectedValue())
                        .getCollection(vista.getjList1().getSelectedValue());

                Document d = Document.parse(vista.getjTextArea1().getText());

                col.insertOne(d);
                carregarDocuments();

            }
            //Borrar documents
            if (actionEvent.getSource().equals(vista.getjButton3())) {

                MongoCollection col = model.getMongoClient().getDatabase(vistaDB.getjList1().getSelectedValue())
                        .getCollection(vista.getjList1().getSelectedValue());

                Document doc = vista.getjList2().getSelectedValue();

                System.out.println(doc.get("_id.timestamp"));

                ObjectId id = (ObjectId) doc.get("_id");
                col.deleteOne(eq("_id", new ObjectId(id.toString())));
                carregarDocuments();
            }
            //Canviar de database
            if (actionEvent.getSource().equals(vista.getjButton7())) {

                vista.setVisible(false);
                vistaDB.setVisible(true);
                carregarKeysCombo();

            }

            if (actionEvent.getSource().equals(vista.getjButton5())) {

                try {
                    MongoCollection col = model.getMongoClient()
                            .getDatabase(vistaDB.getjList1().getSelectedValue())
                            .getCollection(vista.getjList1().getSelectedValue());

                    Document d = vista.getjList2().getSelectedValue();
                    String key = vista.getjComboBox2().getSelectedItem().toString();
                    String value = d.get(key).toString();
                    String newKey = vista.getjTextField1().getText();

                    UpdateResult resultat = col.updateOne(eq(key, value), unset(newKey));

                    carregarDocuments();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Selecciona un document que modificar");
                }

            }

            if (actionEvent.getSource().equals(vista.getjButton4())) {
                try {
                    MongoCollection col = model.getMongoClient()
                            .getDatabase(vistaDB.getjList1().getSelectedValue())
                            .getCollection(vista.getjList1().getSelectedValue());

                    Document d = vista.getjList2().getSelectedValue();
                    String key = vista.getjComboBox2().getSelectedItem().toString();
                    String value = d.get(key).toString();
                    String newKey = vista.getjTextField1().getText();
                    String newValue = vista.getjTextArea2().getText();

                    if (vista.getjTextField1().getText().equals("")) {
                        UpdateResult resultat = col.updateOne(eq(key, value), set(key, newValue));
                    } else if (!vista.getjTextField1().getText().equals("")) {
                        UpdateResult resultat = col.updateOne(eq(key, value), set(newKey, newValue));
                    }

                    carregarDocuments();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Selecciona un document que modificar");
                }

            }

        }

    };

    vista.getjButton6().addActionListener(actionListener);
    vistaDB.getjButton2().addActionListener(actionListener);
    vistaDB.getjButton1().addActionListener(actionListener);
    vista.getjButton1().addActionListener(actionListener);
    vista.getjButton7().addActionListener(actionListener);
    vista.getjButton2().addActionListener(actionListener);
    vista.getjButton3().addActionListener(actionListener);
    vista.getjButton5().addActionListener(actionListener);
    vista.getjButton4().addActionListener(actionListener);

    MouseAdapter mouseAdapter = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);

            if (e.getSource().equals(vista.getjList2())) {
                try {
                    filasel = vista.getjList2().getSelectedIndex();
                    if (filasel != -1) {

                        carregarDocumentsGson();
                        carregarKeysCombo();

                    }
                } catch (NumberFormatException ex) {
                }
            }

            if (e.getSource().equals(vista.getjList1())) {

                try {
                    filasel = vista.getjList1().getSelectedIndex();
                    if (filasel != -1) {
                        carregarDocuments();

                    }
                } catch (NumberFormatException ex) {
                }
            }

        }

    };

    vista.getjList2().addMouseListener(mouseAdapter);
    vista.getjList1().addMouseListener(mouseAdapter);

}

From source file:controller.ProductController.java

public void update(String attr, Object val, Document doc) {
    MongoCollection<Document> booklist = db.getCollection("product");
    booklist.updateOne(eq(attr, val), new Document("$set", doc));
}