Example usage for com.mongodb DBCollection update

List of usage examples for com.mongodb DBCollection update

Introduction

In this page you can find the example usage for com.mongodb DBCollection update.

Prototype

public WriteResult update(final DBObject query, final DBObject update) 

Source Link

Document

Modify an existing document.

Usage

From source file:pruebamongo.PruebaMongo.java

private static void modificarElementos(MongoClient mongo) {
    DB db = mongo.getDB("prueba");
    DBCollection col = db.getCollection("contactos");
    try {/*from   w w  w . j av a  2 s.  c o m*/
        //Instruccin que modifica los elementos
        col.update(new BasicDBObject("_id", 8), //Id que queremos modificar
                new BasicDBObject("$set", //operador para aadir un elemento
                        new BasicDBObject("muerto", "Si")));//valor del nuevo elemento
        System.out.println("Elemento modificado satisfactoriamente.");
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
}

From source file:pubsub.broker.model.Topics.java

public void addSubscriberByHostAddress(String topics, String hostAddress) {
    DBCollection collection = db.getCollection(DBConstants.TOPIC_COLLECTION);
    //BasicDBObject query = new BasicDBObject(DBConstants.TOPIC_TOPIC, topics);

    BasicDBObject query = new BasicDBObject();
    query.put(DBConstants.TOPIC_TOPIC, topics);

    DBObject dbo = collection.findOne(query);

    List<String> hostList = new ArrayList<String>();
    hostList.addAll((List<String>) dbo.get(DBConstants.TOPIC_HOST_LIST));
    hostList.add(hostAddress);//from   w  w w.java 2 s  . c  o m

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put(DBConstants.TOPIC_HOST_LIST, hostList);

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", newDocument);

    collection.update(query, updateObj);
}

From source file:pubsub.broker.model.Topics.java

public void addSubscriberByEmail(String topics, String email) {
    DBCollection collection = db.getCollection(DBConstants.TOPIC_COLLECTION);

    BasicDBObject query = new BasicDBObject();
    query.put(DBConstants.TOPIC_TOPIC, topics);

    DBObject dbo = collection.findOne(query);

    List<String> emailList = new ArrayList<String>();
    emailList.addAll((List<String>) dbo.get(DBConstants.TOPIC_EMAIL_LIST));
    emailList.add(email);//from w w w . ja  v a2 s  .  co  m

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put(DBConstants.TOPIC_EMAIL_LIST, emailList);

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", newDocument);

    collection.update(query, updateObj);

}

From source file:pubsub.broker.model.Topics.java

public void removeSubscriberEmail(String topics, String email) {
    DBCollection collection = db.getCollection(DBConstants.TOPIC_COLLECTION);
    //BasicDBObject query = new BasicDBObject(DBConstants.TOPIC_TOPIC, topics);

    BasicDBObject query = new BasicDBObject();
    query.put(DBConstants.TOPIC_TOPIC, topics);

    DBObject dbo = collection.findOne(query);

    List<String> emailList = new ArrayList<String>();
    emailList.addAll((List<String>) dbo.get(DBConstants.TOPIC_EMAIL_LIST));
    emailList.remove(email);/*from w w w .j ava 2 s . co  m*/

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put(DBConstants.TOPIC_EMAIL_LIST, emailList);

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", newDocument);

    collection.update(query, updateObj);
}

From source file:pubsub.broker.model.Topics.java

public void removeSubscriberHostAddress(String topics, String hostAddress) {
    DBCollection collection = db.getCollection(DBConstants.TOPIC_COLLECTION);

    BasicDBObject query = new BasicDBObject();
    query.put(DBConstants.TOPIC_TOPIC, topics);

    DBObject dbo = collection.findOne(query);

    List<String> hostList = new ArrayList<String>();
    hostList.addAll((List<String>) dbo.get(DBConstants.TOPIC_HOST_LIST));
    hostList.remove(hostAddress);/*from  w  w  w  . j av a  2s . c  o m*/

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put(DBConstants.TOPIC_HOST_LIST, hostList);

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", newDocument);

    collection.update(query, updateObj);
}

From source file:Rpackage.MongoFixPostCode.java

public static void main(String[] args) {

    YelpAPI yelpApi = new YelpAPI();
    JSONParser parser = new JSONParser();
    try {//ww w. jav a 2s.  c  o  m

        // Connect to mongodb
        MongoClient mongo = new MongoClient("10.33.2.142", 27017);

        // get database
        // if database doesn't exists, mongodb will create it for you
        DB db = mongo.getDB("test");

        // get collection
        // if collection doesn't exists, mongodb will create it for you
        DBCollection collection = db.getCollection("twitter_Stream");

        DBCursor cursor;
        BasicDBObject query;
        //------------------------------------
        // ( 1 ) collection.find() --> get all document

        DBObject clause1 = new BasicDBObject("Latitude", new BasicDBObject("$exists", true));
        DBObject clause2 = new BasicDBObject("tweet_Country_Code", new BasicDBObject("$exists", true));
        DBObject clause3 = new BasicDBObject("R_Post_Code", new BasicDBObject("$exists", false));
        /*{
          "$and":[
            {
              "tweet_Country_Code":{
                "$exists":true
              }
            },
            {
              "Latitude":{
                "$exists":false
              }
            },
            {
              "tweet_Country_Code":"AU"
            }
          ]
        }                
        */
        BasicDBList or = new BasicDBList();
        or.add(clause1);
        or.add(clause2);
        or.add(clause3);
        query = new BasicDBObject("$and", or);

        //{  "$and":[    {      "Latitude":{        "$exists":true      }    },    {      "R_Post_Code":{        "$exists":false      }    }  ]}            
        cursor = collection.find(query).addOption(Bytes.QUERYOPTION_NOTIMEOUT) //
                .addOption(Bytes.QUERYOPTION_AWAITDATA);

        System.out.println("( 1 ) .get the user id within  latitide");
        System.out.println("results --> " + cursor.count());
        FoursquareAPI_backup qui4squreApi = new FoursquareAPI_backup();
        try {
            while (cursor.hasNext()) {
                DBObject data = cursor.next();
                String v_user_Name = (String) data.get("user_name");
                Long v_twitte_id = (Long) data.get("tweet_ID");
                String v_twitte_text = (String) data.get("tweet_text");
                Long v_user_Id = (Long) data.get("user_Id");
                Double v_Latitude = (Double) data.get("Latitude");
                Double v_Longtitude = (Double) data.get("Longitude");
                String v_tweet_Place_Name = (String) data.get("tweet_Place_Name");
                String v_tweet_Country_Code = (String) data.get("tweet_Country_Code");

                if (v_user_Id == null) {
                    /*                        System.out.print("update:" +v_user_Name+"/status/"+ v_twitte_id);
                     try{
                     Status status = twitter.showStatus(v_twitte_id);
                     BasicDBObject jo = GetMongoRecord(status);
                     System.out.println( "-->" + status.getId() + " : " + jo.getString("Re_user_screenName") + ":" + jo.getString("tweet_text"));
                     collection.update(new BasicDBObject("tweet_ID", v_twitte_id), jo); // set the document in the DB to the new document for Jo                     
                     }catch (TwitterException ex){
                     if (ex.getStatusCode()==144) continue;
                     }
                     */
                    continue;
                }
                JSONObject businesses = yelpApi.search4Yelp("city", v_Latitude, v_Longtitude);//-27.497835,153.017472);                      
                boolean searchAgain = false;

                if (businesses == null)
                    searchAgain = true;
                else if (businesses.size() < 1)
                    searchAgain = true;

                if (searchAgain) {
                    System.out.println("La:" + v_Latitude + "\tLo:" + v_Longtitude);
                    businesses = qui4squreApi.search4Square("city", v_Latitude, v_Longtitude);
                    searchAgain = false;
                }
                if (businesses == null)
                    searchAgain = true;
                else if (businesses.size() < 1)
                    searchAgain = true;

                if (searchAgain) {
                    businesses = qui4squreApi.searchGoogleMap("city", v_Latitude, v_Longtitude);
                    if (businesses == null) {
                        System.out.println("\t" + v_tweet_Country_Code + "\t:" + v_tweet_Place_Name);
                        continue;
                    } else if (businesses.size() < 1) {
                        System.out.println("\t" + v_tweet_Country_Code + "\t:" + v_tweet_Place_Name);
                        continue;
                    }
                }

                String country_code = (String) businesses.get("country_code");
                String city_code = (String) businesses.get("city_name");
                String state_code = (String) businesses.get("state_code");
                String post_code = (String) businesses.get("post_code");

                BasicDBObject setNewFieldQuery = new BasicDBObject().append("$set",
                        new BasicDBObject().append("R_Country_Code", country_code)
                                .append("R_State_Code", state_code).append("R_City", city_code)
                                .append("R_Post_Code", post_code));

                collection.update(new BasicDBObject().append("tweet_ID", v_twitte_id), setNewFieldQuery); // set the document in the DB to the new document for Jo                                             

                setNewFieldQuery.clear();
                setNewFieldQuery = null;
            }
        } finally {
            cursor.close();
        }

        System.out.println("---------------------------------");

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    }

}

From source file:Server.Service.java

private void check_login(login order) {
    String name = order.getName();
    String pwd = order.getPwd();/*  ww  w .j  a v a2s.  c  o  m*/
    BasicDBObject user = new BasicDBObject().append("name", name);
    DBCollection users = db.getCollection("users");
    DBObject obj = users.findOne(user);

    try {
        if (obj == null) {
            output.writeObject(new login(false, "NO_SUCH_USER"));
            output.flush();
        } else if ((boolean) obj.get("checked")) {
            output.writeObject(new login(false, "USER_CHECKED"));
            output.flush();
        } else if ((boolean) obj.get("locked")) {
            output.writeObject(new login(false, "USER_LOCKED"));
            output.flush();
        } else if (!pwd.equals(obj.get("pwd").toString())) {
            users.update(user, new BasicDBObject().append("$inc", new BasicDBObject().append("wrongTimes", 1)));
            if ((int) obj.get("wrongTimes") == 2) {
                output.writeObject(new login(false, "WRONG_PASSWORD_FIANL"));
                output.flush();
                users.update(user, new BasicDBObject().append("$set", new BasicDBObject("locked", true)));
            } else {
                output.writeObject(new login(false, "WRONG_PASSWORD"));
                output.flush();
            }
        } else {
            BasicDBObject setting = new BasicDBObject().append("checked", true);
            this.currentUser = user;
            users.update(user, new BasicDBObject().append("$set", setting));

            DBCollection clients = db.getCollection("clients");
            clients.update(myClient,
                    new BasicDBObject().append("$set", new BasicDBObject().append("currentUser", currentUser)));

            output.writeObject(new login(true, obj.get("money").toString()));
            output.flush();

            System.out.println(user.get("name") + " logs in " + this.serialNum);
        }
    } catch (IOException ex) {
        Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Server.Service.java

private void check_query(query order) {

    try {/* w ww. j  av  a 2s .c o  m*/
        Date time = new Date();
        double money = 0;
        try {
            if ((order.getAmount() != null) && (!order.getAmount().equals("")))
                money = Double.parseDouble(new String(decrypty(order.getAmount())));
        } catch (NumberFormatException e) {
            output.writeObject(new query(false, "INVALID"));
            output.flush();
            return;
        }

        DBCollection users = db.getCollection("users");
        DBCollection clients = db.getCollection("clients");
        DBCollection records = db.getCollection("records");

        BasicDBObject userQ = new BasicDBObject().append("name", currentUser.getString("name"));
        DBObject user = users.findOne(userQ);
        BasicDBObject clientQ = new BasicDBObject().append("ipAddr", ipAddr);
        DBObject client = clients.findOne(clientQ);

        //DEAL THE QUERY PART
        if (order.type == method.WITHDRAW) {
            double user_money = Double.parseDouble(new String(decrypty(user.get("money").toString())));
            double client_money = Double.parseDouble(new String(decrypty(client.get("money").toString())));
            user_money -= money;
            client_money -= money;

            if (checkNegative(user_money, client_money, money)) {

                String user_money_tmp = encrypt(user_money + "");
                String client_money_tmp = encrypt(client_money + "");
                String user_tmp = "-" + money;

                users.update(userQ, new BasicDBObject().append("$set",
                        new BasicDBObject().append("money", user_money_tmp)));
                records.insert(new BasicDBObject().append("ipAddr", this.ipAddr)
                        .append("serial", this.serialNum).append("name", userQ.getString("name"))
                        .append("type", "WITHDRAW").append("delta", encrypt(user_tmp))
                        .append("remains", user_money_tmp).append("time", formatter.format(time)));
                clients.update(new BasicDBObject().append("ipAddr", ipAddr), new BasicDBObject().append("$set",
                        new BasicDBObject().append("money", client_money_tmp)));

                output.writeObject(new query(true, user_money_tmp));
                output.flush();
            }
        }

        else if (order.type == method.DEPOSIT) {
            double user_money = Double.parseDouble(new String(decrypty(user.get("money").toString())));
            double client_money = Double.parseDouble(new String(decrypty(client.get("money").toString())));
            user_money += money;
            client_money += money;
            if (checkNegative(user_money, client_money, money)) {
                String user_money_tmp = encrypt(user_money + "");
                String client_money_tmp = encrypt(client_money + "");
                String user_tmp = "+" + money;

                users.update(userQ, new BasicDBObject().append("$set",
                        new BasicDBObject().append("money", user_money_tmp)));
                records.insert(new BasicDBObject().append("ipAddr", this.ipAddr)
                        .append("serial", this.serialNum).append("name", userQ.getString("name"))
                        .append("type", "DEPOSIT").append("delta", encrypt(user_tmp))
                        .append("remains", user_money_tmp).append("time", formatter.format(time)));
                clients.update(new BasicDBObject().append("ipAddr", ipAddr), new BasicDBObject().append("$set",
                        new BasicDBObject().append("money", client_money_tmp)));

                output.writeObject(new query(true, user_money_tmp));
                output.flush();
            }
        }

        else if (order.type == method.TRANSFORM) {
            BasicDBObject targetQ = new BasicDBObject().append("name", order.getTarget());
            DBObject target = users.findOne(targetQ);
            if (target == null) {
                output.writeObject(new query(false, "NO_SUCH_USER"));
                output.flush();
            } else if (target.get("name").toString().equals(currentUser.getString("name"))) {
                output.writeObject(new query(false, "NOT_ALLOWED"));
                output.flush();
            } else {
                double user_money = Double.parseDouble(new String(decrypty(user.get("money").toString())));
                double target_money = Double.parseDouble(new String(decrypty(target.get("money").toString())));
                double client_money = Double.parseDouble(new String(decrypty(client.get("money").toString())));
                target_money += money;
                user_money -= money;
                if (checkNegative(user_money, target_money, money)) {
                    String target_money_tmp = encrypt(target_money + "");
                    String user_money_tmp = encrypt(user_money + "");
                    String client_money_tmp = encrypt(client_money + "");
                    String target_tmp = "+" + money;
                    String user_tmp = "-" + money;

                    users.update(userQ, new BasicDBObject().append("$set",
                            new BasicDBObject().append("money", user_money_tmp)));
                    users.update(targetQ, new BasicDBObject().append("$set",
                            new BasicDBObject().append("money", target_money_tmp)));
                    records.insert(new BasicDBObject().append("ipAddr", this.ipAddr)
                            .append("serial", this.serialNum).append("name", userQ.getString("name"))
                            .append("type", "TRANSFORM").append("delta", encrypt(user_tmp))
                            .append("remains", user_money_tmp).append("time", formatter.format(time)));
                    records.insert(new BasicDBObject().append("ipAddr", this.ipAddr)
                            .append("serial", this.serialNum).append("name", targetQ.getString("name"))
                            .append("type", "TRANSFORM").append("delta", encrypt(target_tmp))
                            .append("remains", target_money_tmp).append("time", formatter.format(time)));
                    clients.update(new BasicDBObject().append("ipAddr", ipAddr), new BasicDBObject()
                            .append("$set", new BasicDBObject().append("money", client_money_tmp)));

                    output.writeObject(new query(true, user_money_tmp));
                    output.flush();
                }
            }
        }

        else if (order.type == method.LOOKUP) {
            DBCursor cursor = records.find(userQ);
            ArrayList<tradeD> details = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject tmp = cursor.next();
                tradeD obj = new tradeD(tmp.get("serial").toString(), tmp.get("ipAddr").toString(),
                        tmp.get("name").toString(), tmp.get("type").toString(), tmp.get("delta").toString(),
                        tmp.get("remains").toString(), tmp.get("time").toString());
                details.add(obj);
            }
            output.writeObject(new query(true, "", details));
            output.flush();
        }

        else if (order.type == method.RESET) {
            String pwd = user.get("pwd").toString();
            if (order.getPwd0().equals(pwd) && (order.getPwd1() != null)) {
                users.update(currentUser,
                        new BasicDBObject().append("$set", new BasicDBObject().append("pwd", order.getPwd1())));
                output.writeObject(new query(true, "Success"));
                output.flush();
            } else {
                output.writeObject(new query(false, "wrongPwd"));
                output.flush();
            }
        }

    } catch (java.lang.NullPointerException ex) {
        Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
        this.DBShutdown();
    } catch (IOException ex) {
        this.DBShutdown();
        Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Server.Service.java

private void check_logout() {
    if (currentUser != null) {
        DBCollection users = db.getCollection("users");
        users.update(currentUser,
                new BasicDBObject().append("$set", new BasicDBObject().append("checked", false)));
        DBCollection clients = db.getCollection("clients");
        clients.update(myClient,// w  w  w  .j a v a2s.  c  o  m
                new BasicDBObject().append("$set", new BasicDBObject().append("currentUser", null)));
        System.out.println(this.currentUser.get("name").toString() + " logged out @" + this.serialNum);
        this.currentUser = null;
    }
}

From source file:serwlety.dodaj.DokumentServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w  ww.  j a  v a2 s .c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DBCollection db = baza.FabrykaPolaczenia.getInstance().getConnection().getCollection("Osoba");
    BasicDBObject obiekt = new BasicDBObject();
    obiekt.append("nazwa", request.getParameter("nazwa")).append("tagi", request.getParameterValues("tagi"));
    ArrayList<String> pliki = new ArrayList<>();
    for (Part plik : request.getParts().stream().filter(part -> "plik".equals(part.getName()))
            .collect(Collectors.toList())) {
        String nazwa = plik.getName() + Math.random();
        //Files.copy(plik.getInputStream(), new File("/home/mat-bi/NetBeansProjects/MongoTAB2/web/pliki",nazwa).toPath());
        Files.copy(plik.getInputStream(), new File("C:\\Users\\JG\\Desktop", nazwa).toPath());
        pliki.add(nazwa);
    }
    obiekt.append("pliki", pliki);
    BasicDBObject findOne = (BasicDBObject) db
            .findOne(new BasicDBObject("_id", new ObjectId(request.getParameter("id"))));
    if (findOne.get("dokumenty") == null) {
        findOne.append("dokumenty", new BasicDBList());
    }

    if (request.getParameterValues("dodatkowe") != null) {
        ArrayList<BasicDBObject> lista = new ArrayList<>();
        int i = 0;
        for (String dodatkowe : request.getParameterValues("dodatkowe")) {
            lista.add(new BasicDBObject(dodatkowe, request.getParameterValues("dodatkowe_wartosc")[i++]));
        }
        obiekt.append("dodatkowe", lista);
    }
    ((BasicDBList) findOne.get("dokumenty")).add(obiekt);
    db.update(new BasicDBObject("_id", new ObjectId(request.getParameter("id"))), findOne);
    request.getRequestDispatcher("/WEB-INF/dodaj/dokument_dodany.jsp").forward(request, response);
}