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:dto.Dto.java

public void rechazarSolicitudAsesor(String idTesis) {
    MongoCollection<Document> col = c.getConnection("tesis_alumno_asesor");
    Document doc = col.find(eq("_id", idTesis)).first();
    col.updateOne(doc, new Document("$set", new Document("estadoA", "rechazado")));

    MongoCollection<Document> col1 = c.getConnection("tesis_alumno_asesor");
    Document doc2 = col1.find(eq("_id", idTesis)).first();
    col.updateOne(doc2, new Document("$set", new Document("idAsesor", 0)));
}

From source file:dto.Dto.java

public void aceptarActa(String idActa) {
    MongoCollection<Document> col = c.getConnection("actas");
    Document doc = col.find(eq("_id", idActa)).first();

    col.updateOne(doc, new Document("$set", new Document("estado", "aceptado")));
}

From source file:dto.Dto.java

public void rechazarActa(String idActa) {
    MongoCollection<Document> col = c.getConnection("actas");
    Document doc = col.find(eq("_id", idActa)).first();

    col.updateOne(doc, new Document("$set", new Document("estado", "rechazado")));
}

From source file:edu.uniandes.ecos.codeaholics.config.DataBaseUtil.java

/**
 * Actualiza un registro en la base de datos
 * //ww w.  ja  v  a2  s.  c  o m
 * @param pFilter
 *            documento filtro
 * @param pRegister
 *            registro para actualizar
 * @param pCollection
 *            coleccion en donde actulizarlo
 * @throws MongoWriteException
 *             exception de mongo
 */
public static void update(Document pFilter, Document pRegister, String pCollection) throws MongoWriteException {
    // create JSON with the $SET parameter (It's use to update a register in
    // the DB)
    Document registerOperator = new Document();
    registerOperator.append("$set", pRegister);

    // get the collection
    MongoCollection<Document> collection = db.getCollection(pCollection);

    // update the DB
    log.debug("Updating " + pRegister);
    log.debug("In Collection " + pCollection);
    try {
        collection.updateOne(pFilter, registerOperator);
        log.info("-----------------------------------");
        log.info("Successful Updated");
        log.info("-----------------------------------");
    } catch (MongoException e) {
        log.info(e.getMessage());
        throw e;
    }
}

From source file:edu.uniandes.ecos.codeaholics.config.DataBaseUtil.java

/**
 * Actualiza un campo a partir de una consulta inclusiva con el operador
 * $and//  w w  w .  ja  v a  2  s  . c o m
 *
 */

public static void compositeUpdate(List<Document> pFilter, Document pRegister, String pCollection)
        throws MongoWriteException {

    Document filterOperator = new Document();
    filterOperator.append("$and", pFilter);

    Document registerOperator = new Document();
    registerOperator.append("$set", pRegister);

    MongoCollection<Document> collection = db.getCollection(pCollection);

    try {
        collection.updateOne(filterOperator, registerOperator);
    } catch (MongoException e) {
        log.info(e.getMessage());
        throw e;
    }

}

From source file:eu.vre4eic.evre.telegram.commands.RegisterAuthCommand.java

License:Apache License

@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

    String userName = user.getFirstName() + " " + user.getLastName();
    StringBuilder messageBuilder = new StringBuilder();
    if (arguments.length != 2) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("please use: /register username pwd");
    } else {/* ww w  .ja  va2  s.  c o  m*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("evre");
        MongoCollection<Document> collection = db.getCollection("eVREUserProfile");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userId", arguments[0]);
        FindIterable<Document> itcursor = collection.find(searchQuery);
        //FindIterable<Document> itcursor=collection.find();
        MongoCursor<Document> cursor = itcursor.iterator();
        if (cursor.hasNext()) {

            Document userCan = cursor.next();
            String pwd = userCan.getString("password");

            Binary binS = userCan.get("salt", org.bson.types.Binary.class);
            String salt = new String(binS.getData());
            boolean validUser = false;
            if (pwd.equals(arguments[1]))
                validUser = true;

            if (salt != null && !checkEncryptedData(arguments[1], salt.getBytes()).equals(arguments[1]))
                validUser = true;

            //if(pwd.equals(arguments[1])){
            if (validUser) {

                userCan.replace("authId", chat.getId());
                BasicDBObject updateObj = new BasicDBObject();
                updateObj.put("$set", userCan);
                //check this!!!
                collection.updateOne(searchQuery, updateObj);

                messageBuilder.append("Done ").append(userName).append(",\n");
                messageBuilder.append(
                        "this Telegram account is now registered as e-VRE Authenticator for " + arguments[0]);

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append("\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }

}

From source file:eu.vre4eic.evre.telegram.commands.RemoveAuthCommand.java

License:Apache License

@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

    String userName = user.getFirstName() + " " + user.getLastName();
    StringBuilder messageBuilder = new StringBuilder();
    if (arguments.length != 2) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("please use: /remove username pwd");
    } else {/*w ww  .j  ava  2s  . c  o m*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("evre");
        MongoCollection<Document> collection = db.getCollection("eVREUserProfile");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userId", arguments[0]);
        FindIterable<Document> itcursor = collection.find(searchQuery);
        //FindIterable<Document> itcursor=collection.find();
        MongoCursor<Document> cursor = itcursor.iterator();
        if (cursor.hasNext()) {
            //System.out.println("################## "+cursor.next());
            Document userCan = cursor.next();
            String pwd = userCan.getString("password");
            if (pwd.equals(arguments[1])) {

                String aId = userCan.getString("authId");
                if (!aId.equals("0")) {
                    // we don't check if the chat.getId() is the same,
                    //because a user can remove this from another Telegram ID,
                    // need to check this

                    userCan.replace("authId", "0");
                    BasicDBObject updateObj = new BasicDBObject();
                    updateObj.put("$set", userCan);
                    //check this!!!
                    collection.updateOne(searchQuery, updateObj);

                    messageBuilder.append("Done ").append(userName).append(", \n");
                    messageBuilder.append(
                            "this Telegram account is no longer an e-VRE Authenticator for " + arguments[0]);
                } else {//the user with the provided credentials has no authenticator defined
                    messageBuilder.append("Hi ").append(userName).append(",\n");
                    messageBuilder.append("something went wrong, please contact the administrator!");
                }

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append(",\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }
}

From source file:examples.tour.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 */// w  w  w . j  a va 2s. co  m
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
            new Document("x", 203).append("y", 102));

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    Block<Document> printBlock = new Block<Document>() {

        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);

    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());

    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());

    // Aggregation
    collection
            .aggregate(
                    asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}"))))
            .forEach(printBlock);

    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), set("i", 110));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("i", 110));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    //collection.find().forEach(printBlock);

    // Clean up
    database.drop();

    // release resources
    mongoClient.close();
}

From source file:if4031.ServerHandler.java

private boolean subscribeChannel(String token, String channel) {
    MongoCollection<Document> userCollection = database.getCollection("User");
    Document channelDoc = new Document("name", channel);
    Document listChannel = new Document("channels", channel);
    userCollection.updateOne(eq("nick", token), new Document("$push", listChannel));
    //userCollection.updateOne(eq("nick", token), new Document("$set",new Document("channel", channel)));
    return true;/*w w w.  j  a  va 2  s  .  c  o m*/
}

From source file:if4031.ServerHandler.java

@Override
public String deleteMember(String token, String channel) throws TException {
    MongoCollection<Document> userCollection = database.getCollection("User");
    Document match = new Document("nick", token);
    Document remove = new Document("channels", channel);
    userCollection.updateOne(match, new Document("$pull", remove));
    //        userCollection.updateOne(eq("nick",token), new Document("$pull", remove));
    return "Channel unsubscribed.";
}