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:Welcome.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    /*MongoClient client = new MongoClient("localhost", 27017);
        DB db;/*  www  .  j a v  a2 s.  c o  m*/
        db = client.getDB("ExpenseManager");
        DBCollection reg = (DBCollection) db.getCollection("Registration");
        DBObject query = new BasicDBObject("unm", unm);
        DBObject update = new BasicDBObject();
                
        update.put("$unset", new BasicDBObject("userId",""));
    */
    int i = 1;
    int count = 1;
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase db = client.getDatabase("ExpenseManager");
    MongoCollection<Document> reg = db.getCollection("Registration");
    FindIterable<Document> find = reg.find(new Document("unm", unm));
    DBObject query = new BasicDBObject("unm", unm);
    BasicDBObject update = new BasicDBObject();
    Map<Integer, Integer> m = new HashMap<Integer, Integer>();
    String val[] = new String[6];
    val[0] = "";
    Document doc = find.first();
    while (i <= 5) {
        if (!doc.containsKey("Account" + i)) {
            i++;
        } else {
            while (doc.containsKey("Account" + i)) {
                m.put(count, i);
                val[count] = (String) (doc.get("Account" + i));
                i++;
                count++;
            }
        }
    }
    JComboBox jcb = new JComboBox(val);
    jcb.setEditable(true);
    int msg = JOptionPane.showConfirmDialog(this, "Do You Really Want to remove Your Account?");
    if (msg == 0) {
        JOptionPane.showMessageDialog(this, jcb, "Select Your Account to Remove", JOptionPane.QUESTION_MESSAGE);

        while (jcb.getSelectedItem().equals("")) {
            JOptionPane.showMessageDialog(this, "You Haven't chose any Account, Please Choose the Account");
            JOptionPane.showMessageDialog(this, jcb, "Select Your Account to Remove",
                    JOptionPane.QUESTION_MESSAGE);
        }
        int index = jcb.getSelectedIndex();
        int value = m.get(index);
        String str1 = "Account" + value;
        String str2 = "Bank" + value;
        String str3 = "Money" + value;
        update.put("$unset", new BasicDBObject(str1, "").append(str2, "").append(str3, ""));
        UpdateResult updateOne = reg.updateOne(new Document("unm", unm), update);
        setListVal();

    }

    // TODO add your handling code here:
}

From source file:anuncius.singleton.MongoHandler.java

public boolean delete(int id, String collectionName) {
    MongoCollection<Document> collection = mainDatabase.getCollection(collectionName);
    Document document = new Document();
    document.put("_id", id);
    document.put("deleted", true);
    UpdateResult result = collection.updateOne(document, document);
    return result.getModifiedCount() >= 1;
}

From source file:ch.hslu.dmg.InitDB.java

public void initVorlesungen() {
    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase database = mongo.getDatabase("unidb");
    MongoCollection<Document> vorlesung = database.getCollection("vorlesungen");
    vorlesung.drop();/*from w ww  . j a v  a 2  s  .c o m*/

    ArrayList<Document> vorlesungen = new ArrayList<>();
    vorlesungen.add(new Document("VorlNr", 5001).append("Titel", "Grundzge").append("SWS", 4)
            .append("GelesenVon", 2137));
    vorlesungen.add(
            new Document("VorlNr", 5041).append("Titel", "Ethik").append("SWS", 4).append("GelesenVon", 2125));
    vorlesungen.add(new Document("VorlNr", 5043).append("Titel", "Erkentnistheorie").append("SWS", 3)
            .append("GelesenVon", 2126));
    vorlesungen.add(new Document("VorlNr", 5049).append("Titel", "Maeeutik").append("SWS", 2)
            .append("GelesenVon", 2125));
    vorlesungen.add(
            new Document("VorlNr", 4052).append("Titel", "Logik").append("SWS", 4).append("GelesenVon", 2125));
    vorlesungen.add(new Document("VorlNr", 5052).append("Titel", "Wissenschaftstheorie").append("SWS", 3)
            .append("GelesenVon", 2126));
    vorlesungen.add(new Document("VorlNr", 5216).append("Titel", "Bioethik").append("SWS", 2)
            .append("GelesenVon", 2126));
    vorlesungen.add(new Document("VorlNr", 5259).append("Titel", "Der Wiener Kreis").append("SWS", 2)
            .append("GelesenVon", 2133));
    vorlesungen.add(new Document("VorlNr", 5022).append("Titel", "Glaube und Wissen").append("SWS", 2)
            .append("GelesenVon", 2134));
    vorlesungen.add(new Document("VorlNr", 4630).append("Titel", "Die 3 Kritiken").append("SWS", 4)
            .append("GelesenVon", 2137));

    vorlesung.insertMany(vorlesungen);

    vorlesung.updateOne(eq("VorlNr", 5041), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5001)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5043), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5001)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5049), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5001)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5216), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5041)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5259), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5052)).iterator().next().get("_id"))));
    BasicDBList voraussetzungen = new BasicDBList();
    voraussetzungen.add(vorlesung.find(eq("VorlNr", 5043)).iterator().next().get("_id"));
    voraussetzungen.add(vorlesung.find(eq("VorlNr", 5041)).iterator().next().get("_id"));
    vorlesung.updateOne(eq("VorlNr", 5052),
            new Document("$set", new Document("Voraussetzung", voraussetzungen)));

    mongo.close();
}

From source file:co.aurasphere.mongodb.university.classes.m101j.homework31.MainClass.java

License:Open Source License

/**
 * The main method.//from   w  w  w  .j a  v a2 s.  c o  m
 *
 * @param args
 *            the arguments
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("school");
    MongoCollection<Document> students = db.getCollection("students");

    // Gets all the students.
    MongoCursor<Document> cursor = students.find().iterator();

    try {
        while (cursor.hasNext()) {
            Document student = cursor.next();
            List<Document> scores = (List<Document>) student.get("scores");

            // Finds the lowest homework score.
            Document minScoreObj = null;
            double minScore = Double.MAX_VALUE;

            for (Document scoreDocument : scores) {
                double score = scoreDocument.getDouble("score");
                String type = scoreDocument.getString("type");

                // Swaps the scores.
                if (type.equals("homework") && score < minScore) {
                    minScore = score;
                    minScoreObj = scoreDocument;
                }
            }

            // Removes the lowest score.
            if (minScoreObj != null) {
                scores.remove(minScoreObj);
            }

            // Updates the record.
            students.updateOne(Filters.eq("_id", student.get("_id")),
                    new Document("$set", new Document("scores", scores)));
        }

        // Gets the student with the highest average in the class.
        AggregateIterable<Document> results = students.aggregate(Arrays.asList(Aggregates.unwind("$scores"),
                Aggregates.group("$_id", Accumulators.avg("average", "$scores.score")),
                Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1)));

        // There should be only one result. Prints it.
        System.out.println("Solution : " + results.iterator().next().toJson());

    } finally {
        cursor.close();
    }

    client.close();
}

From source file:com.andersen.backendjaxrsproject.EmployeeServices.java

public String updateEmployee(long employeeID, String key, String updatedValue) {
    String newString = "";
    MongoCollection<Document> employeeCollection = employeeDB.getCollection("EmployeeCollection");
    ObjectMapper mapper = new ObjectMapper();

    Bson newValue = new Document(key, updatedValue);
    Bson filter = new Document("id", employeeID);
    Bson updateOperationDoc = new Document("$set", newValue);

    //Update the employee information
    UpdateResult result = employeeCollection.updateOne(filter, updateOperationDoc);

    //get the document back from the database to verify that it was added
    Bson bson = (Bson) com.mongodb.util.JSON.parse("{'id': " + employeeID + "}");

    FindIterable<Document> find = employeeCollection.find();
    FindIterable<Document> filteredQuery = find.filter(bson);
    for (Document document : filteredQuery) {
        newString = newString + document.toJson() + "\n";
    }//from w  w w. j  ava 2s  .  co  m
    return newString;
}

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

License:Open Source License

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 data = getNamedParam(argStruct, "data", null);
    if (data == null)
        throwException(_session, "please specify data to save");

    try {//  w  w w .  j  a v a 2s .c o  m
        Document doc = getDocument(data);
        MongoCollection<Document> col = db.getCollection(collection);
        long start = System.currentTimeMillis();

        if (doc.containsKey("_id")) {
            col.updateOne(new Document("_id", doc.get("_id")), new Document("$set", doc));
        } else {
            col.insertOne(doc);
        }

        _session.getDebugRecorder().execMongo(col, "save", doc, System.currentTimeMillis() - start);

        return cfBooleanData.TRUE;

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

From source file:com.cognitive.cds.invocation.mongo.WorkProductDao.java

License:Apache License

public UpdateResult updateWorkProduct(WorkProduct wp) throws JsonProcessingException {
    mongoDbDao.setDatabase("work");
    MongoClient mongo = mongoDbDao.getMongoClient();
    MongoDatabase db = mongo.getDatabase("work");
    MongoCollection<Document> collection = db.getCollection("work");

    Document filter = new Document();
    if (wp.getId() == null)
        return null;
    else//  w ww.j  a v  a2 s . c o  m
        filter.put("_id", new ObjectId(wp.getId()));

    Document obj = collection.find(filter).first();
    UpdateResult result = null;

    if (obj != null) {
        try {
            String objectJson = JsonUtils.getMapper().writeValueAsString(wp);
            Document doc = Document.parse(objectJson);
            result = collection.updateOne(filter, new Document("$set", new Document("workproduct", doc)));

        } catch (IOException e) {
            logger.error("========> Deserialize: " + e.toString());
        }
    }
    return result;
}

From source file:com.epam.dlab.auth.dao.UserInfoDAOMongoImpl.java

License:Apache License

@Override
public void updateUserInfoTTL(String accessToken, UserInfo ui) {
    //Update is caleed often, but does not need to be synchronized with the main thread

    BasicDBObject uiDoc = new BasicDBObject();
    uiDoc.put("_id", accessToken);
    uiDoc.put("expireAt", new Date(System.currentTimeMillis()));
    MongoCollection<BasicDBObject> security = ms.getCollection("security", BasicDBObject.class);
    security.updateOne(new BasicDBObject("_id", accessToken), new BasicDBObject("$set", uiDoc));
    log.debug("Updated persistent {}", accessToken);

}

From source file:com.epam.dlab.mongo.DlabResourceTypeDAO.java

License:Apache License

/**
 * Update exploratory cost in Mongo DB./*from w w  w.ja v a2 s  .c  o m*/
 *
 * @param user            the name of user.
 * @param exploratoryName id of exploratory.
 */
private void updateExploratoryCost(String user, String exploratoryName) {
    LOGGER.debug("Update explorartory {} cost for user {}", exploratoryName, user);
    List<? extends Bson> pipeline = Arrays.asList(
            match(and(eq(FIELD_USER, user), eq(FIELD_EXPLORATORY_NAME, exploratoryName))),
            group(getGrouppingFields(FIELD_DLAB_RESOURCE_ID, ReportLine.FIELD_PRODUCT,
                    ReportLine.FIELD_RESOURCE_TYPE, ReportLine.FIELD_CURRENCY_CODE),
                    sum(ReportLine.FIELD_COST, "$" + ReportLine.FIELD_COST),
                    min(FIELD_USAGE_DATE_START, "$" + ReportLine.FIELD_USAGE_DATE),
                    max(FIELD_USAGE_DATE_END, "$" + ReportLine.FIELD_USAGE_DATE)),
            sort(new Document(FIELD_ID + "." + FIELD_DLAB_RESOURCE_ID, 1)
                    .append(FIELD_ID + "." + ReportLine.FIELD_PRODUCT, 1)));
    AggregateIterable<Document> docs = connection.getCollection(COLLECTION_BILLING).aggregate(pipeline);
    LinkedList<Document> billing = new LinkedList<>();
    ResourceItemList resources = getResourceList();
    Double costTotal = null;
    String currencyCode = null;
    for (Document d : docs) {
        Document id = (Document) d.get(FIELD_ID);
        double cost = BillingCalculationUtils.round(d.getDouble(ReportLine.FIELD_COST), 2);
        costTotal = (costTotal == null ? cost : costTotal + cost);
        if (currencyCode == null) {
            currencyCode = id.getString(ReportLine.FIELD_CURRENCY_CODE);
        }

        Document total = new Document()
                .append(FIELD_RESOURCE_NAME,
                        resources.getById(id.getString(FIELD_DLAB_RESOURCE_ID)).getResourceName())
                .append(ReportLine.FIELD_PRODUCT, id.getString(ReportLine.FIELD_PRODUCT))
                .append(ReportLine.FIELD_RESOURCE_TYPE, id.getString(ReportLine.FIELD_RESOURCE_TYPE))
                .append(ReportLine.FIELD_COST, BillingCalculationUtils.formatDouble(cost))
                .append(ReportLine.FIELD_CURRENCY_CODE, id.getString(ReportLine.FIELD_CURRENCY_CODE))
                .append(FIELD_USAGE_DATE_START, d.getString(FIELD_USAGE_DATE_START))
                .append(FIELD_USAGE_DATE_END, d.getString(FIELD_USAGE_DATE_END));
        billing.add(total);
    }

    LOGGER.debug("Total explorartory {} cost for user {} is {} {}, detail count is {}", exploratoryName, user,
            costTotal, currencyCode, billing.size());
    billing.sort(new BillingComparator());

    MongoCollection<Document> cExploratory = connection.getCollection(COLLECTION_USER_INSTANCES);
    Bson values = Updates.combine(
            Updates.set(ReportLine.FIELD_COST, BillingCalculationUtils.formatDouble(costTotal)),
            Updates.set(FIELD_CURRENCY_CODE, currencyCode),
            Updates.set(COLLECTION_BILLING, (!billing.isEmpty() ? billing : null)));
    cExploratory.updateOne(and(and(eq(FIELD_USER, user), eq(FIELD_EXPLORATORY_NAME, exploratoryName))), values);
}

From source file:com.epam.dlab.mongo.DlabResourceTypeDAO.java

License:Apache License

/**
 * Update EDGE cost in Mongo DB.//  w  ww .  ja v  a 2s  . c  o  m
 *
 * @param user the name of user.
 */
private void updateEdgeCost(String user) {
    List<? extends Bson> pipeline = Arrays.asList(
            match(and(eq(FIELD_USER, user), eq(FIELD_EXPLORATORY_NAME, null))),
            group(getGrouppingFields(ReportLine.FIELD_CURRENCY_CODE),
                    sum(ReportLine.FIELD_COST, "$" + ReportLine.FIELD_COST)));
    AggregateIterable<Document> docs = connection.getCollection(COLLECTION_BILLING_TOTAL).aggregate(pipeline);

    MongoCollection<Document> cEdge = connection.getCollection(COLLECTION_USER_EDGE);
    for (Document d : docs) {
        Document id = (Document) d.get(FIELD_ID);
        Bson values = Updates.combine(
                Updates.set(ReportLine.FIELD_COST,
                        BillingCalculationUtils.round(d.getDouble(ReportLine.FIELD_COST), 2)),
                Updates.set(FIELD_CURRENCY_CODE, id.get(ReportLine.FIELD_CURRENCY_CODE)));
        cEdge.updateOne(eq(FIELD_ID, user), values);
    }
}