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

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    try {/*ww  w . j  av  a2s  .  c om*/
        out = response.getWriter();
        String id = request.getParameter("id");
        status = request.getParameter("type");
        System.out.println("id received : " + id);
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        // Now connect to your databases
        DB db = mongoClient.getDB("XHiring");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("users");
        System.out.println("Collection users selected successfully");
        //read example
        try {
            BasicDBObject query = new BasicDBObject("_id", new ObjectId(id));
            BasicDBObject update;
            if (status != null && status.equalsIgnoreCase(" ")) {
                update = new BasicDBObject("isAdmin", "true");
            } else {
                update = new BasicDBObject("isAdmin", "false");
            }
            coll.update(query, update);
            success = new JSONObject();
            success.put("message", "document updated");
            out.println(success);
        } catch (NullPointerException ex) {
            error = new JSONObject();
            error.put("message", "No result found");
            out.println(error);
        }
        System.out.println("Document updated successfully");
    } catch (Exception e) {
        exception = new JSONObject();
        try {
            exception.put("message", "exception");
            out.println(exception);
        } catch (JSONException ex) {
            Logger.getLogger(ChangeUserRole.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:amazonwebcrawler.Mongo.java

public void searchAndReplaceData(DBCollection table, String[] args) {
    try {//from   w  w  w .  j  a v  a  2 s .c  o m
        BasicDBObject query = new BasicDBObject();
        query.put("name", "mkyong");

        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("name", "mkyong-updated");

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

        table.update(query, updateObj);
    } catch (MongoException e) {
        e.printStackTrace();
    }
}

From source file:applango.common.services.DB.mongo.mongoDB.java

public static void updateLicensePrice(DBCollection appInfoConnection, String licenseType, int newPrice) {
    System.out.println("Updating license price of " + licenseType + " to " + newPrice);
    String jsonCustomer = "{$and : [{'licenseType' : '" + licenseType
            + "'}, {'customerId': 'automationCustomer'} ]}";
    DBObject dbObjectRecordQuery = (DBObject) JSON.parse(jsonCustomer);

    BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("price", newPrice));
    appInfoConnection.update(dbObjectRecordQuery, set);
    System.out.println("The new price for " + licenseType + " is " + newPrice);

}

From source file:applango.common.services.DB.mongo.mongoDB.java

public static void updateCustomerAppRankWeightSet(DBCollection appInfoConnection, String weightName,
        boolean defaultWeightSet) {

    System.out.println("Updating " + weightName + " to " + defaultWeightSet);
    String jsonCustomer = "{$and : [{'weightName' : '" + weightName
            + "'}, {'customerId': 'automationCustomer'} ]}";
    DBObject dbObjectRecordQuery = (DBObject) JSON.parse(jsonCustomer);

    BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("defaultWeightSet", defaultWeightSet));
    appInfoConnection.update(dbObjectRecordQuery, set);
    System.out.println("CustomerAppRankWeightSet for " + weightName + " is " + defaultWeightSet);

}

From source file:br.rdu.ifpb.mongo.repositorio.PessoaRepositoriMongo.java

@Override
public int upDate(Pessoa pessoa) {
    DB db = getConnection();//from w w w  .j a v a 2s  .c  o m
    DBCollection table = db.getCollection("pessoa");
    BasicDBObject query = new BasicDBObject();
    query.put("nome", pessoa.getNome());

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put("nome", pessoa.getNome());
    newDocument.put("cpf", pessoa.getCpf());
    newDocument.put("idade", pessoa.getIdade());

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

    result = table.update(query, updateObj).getN();
    closeConnection(mongo);
    return result;
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public boolean modify(String tableName, String json, String _id) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("") || _id == null
            || _id.equals("")) {
        return false;
    }//from w ww.j a  v  a  2  s.  c o m
    DBCollection table = db.getCollection(tableName);
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", new ObjectId(_id));
    DBObject dbObject = (DBObject) JSON.parse(json);
    dbObject.put("update", System.currentTimeMillis() + "");
    WriteResult result = table.update(searchQuery, dbObject);
    return result.isUpdateOfExisting();
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public boolean modifyByCondition(String tableName, String json, Map condition) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("") || condition == null
            || condition.isEmpty()) {//  ww  w .j  a v  a 2 s .c  o  m
        return false;
    }
    DBCollection table = db.getCollection(tableName);
    BasicDBObject searchQuery = new BasicDBObject(condition);
    DBObject dbObject = (DBObject) JSON.parse(json);
    dbObject.put("update", System.currentTimeMillis() + "");
    WriteResult result = table.update(searchQuery, dbObject);
    return result.isUpdateOfExisting();
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public List<Boolean> modifyNotOveride(String tableName, String json, String _id) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("") || _id == null
            || _id.equals("")) {
        return null;
    }// w ww  . j  av  a 2 s . co  m
    List<Boolean> resList = new ArrayList();
    DBCollection table = db.getCollection(tableName);
    DBCursor cursor = table.find();
    while (cursor.hasNext()) {
        DBObject updateDocument = cursor.next();
        DBObject searchQuery = cursor.next();
        DBObject dbObject = (DBObject) JSON.parse(json);
        updateDocument.putAll(dbObject.toMap());
        updateDocument.removeField("_id");
        WriteResult result = table.update(searchQuery, updateDocument);
        resList.add(result.isUpdateOfExisting());
    }
    return resList;
}

From source file:BusinessLogic.Service.RestaurantService.java

public String update(
        //String name, String direccion, String phone) {
        Restaurant rs) {/*from  w w  w. ja  v  a2  s  .  c om*/
    String name = rs.getName();
    String direccion = rs.getAddress();
    String phone = rs.getPhone();
    String reservationUpdate = null;
    try {
        // To connect to mongo dbserver
        MongoConnection dbSingleton = MongoConnection.getInstance();
        DB db = dbSingleton.getTestdb();
        DBCollection coll = db.getCollection(collName);

        System.out.println("Collection restaurants selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        // Sentence to search one account number
        whereQuery.put("name", name);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {

            DBObject updateDocument = cursor.next();
            updateDocument.put("name", name);
            updateDocument.put("direccion", direccion);
            updateDocument.put("phone", phone);

            coll.update(whereQuery, updateDocument);

        }
        System.out.println("Document updated successfully");
        reservationUpdate = "Success";

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (reservationUpdate != null) {
        return "The restaurant has been updated successfully!";
    } else {
        return "The restaurant has not been updated!";
    }
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * Update one field of a database document
 * @param coll the collection the document is in
 * @param findField the field to look for
 * @param findValue the field value to search for
 * @param setField the field to set//ww  w .  j  a  va 2s  . c o m
 * @param setValue the new field value
 * @throws DbException 
 */
public void updateByField(String coll, String findField, Object findValue, String setField, Object setValue)
        throws DbException {
    try {
        connect();
        DBCollection collection = getCollectionFromName(coll);
        if (findField.equals(JSONKeys._ID))
            findValue = new ObjectId((String) findValue);
        BasicDBObject update = new BasicDBObject("$set", new BasicDBObject(setField, setValue));
        BasicDBObject query = new BasicDBObject();
        query.put(findField, findValue);
        WriteResult res = collection.update(query, update);
    } catch (Exception e) {
        throw new DbException(e);
    }
}