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:com.tml.pathummoto.Dao.PartDao.java

public void addstock(int t, String p) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("part");
    BasicDBObject updateQuery = new BasicDBObject();
    updateQuery.append("$set", new BasicDBObject().append("quant", t));
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.append("_id", p);
    coll.update(searchQuery, updateQuery);
    ////from   w w  w .  java  2  s.  co m

    /*BasicDBObject updateQuery = new BasicDBObject();
    updateQuery.append("$set",
    new BasicDBObject().append("clients", "888"));
            
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.append("type", "vps");
            
    collection.update(searchQuery, updateQuery);*/
}

From source file:com.xemsdoom.xeco.core.storage.mongodb.MongoDBStorage.java

License:Open Source License

@Override
public boolean saveAccounts(Set<Account> accounts, Set<String> deleted) {

    Tracker.log("Attempting to save Accounts in MongoDB...");
    long start = System.currentTimeMillis();

    DBCollection coll = db.getCollection(collection);

    // Remove deleted accounts from collection
    for (String acc : deleted) {
        coll.remove(new BasicDBObject("_id", acc));
    }//w  w  w. j av a 2s  . c  om

    // Update, Insert
    for (Account acc : accounts) {

        BasicDBObject query = new BasicDBObject("_id", acc.getAccountName());
        DBCursor cursor = coll.find(query);

        // Check if document already exists
        if (cursor.hasNext()) {

            DBObject old = cursor.next();
            BasicDBObject update = new BasicDBObject();

            // Update
            update.put("_id", acc.getAccountName());
            update.put("balance", acc.getBalance());
            update.put("freezed", acc.isFrozen());
            coll.update(old, update);

        } else {

            // Insert
            BasicDBObject insert = new BasicDBObject("_id", acc.getAccountName())
                    .append("balance", acc.getBalance()).append("freezed", acc.isFrozen());
            coll.insert(insert);
        }
    }

    Tracker.log("Saving Accounts in MongoDB took: "
            .concat(String.valueOf((System.currentTimeMillis() - start)).concat("ms.")));
    Tracker.log("Saved " + accounts.size() + " and deleted " + deleted.size() + " Accounts.");
    return true;
}

From source file:dao.CocinaDAO.java

public Integer actualizarEstado(int idPedido, String username) {
    int idestado;
    ConexionMLab con = new ConexionMLab();
    MongoClient mongo = con.getConexion();
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date fecha = new Date();
    int fields = 0;
    try {//from   ww w  .j a  v a2  s  .  co  m
        DB db = mongo.getDB("pizzaplaneta");
        DBCollection coleccion = db.getCollection("pedido");
        BasicDBObject query = new BasicDBObject();
        query.put("_id", idPedido);
        DBCursor cursor = coleccion.find(query);

        DBObject dbo = cursor.next();
        BasicDBList dbo1 = (BasicDBList) dbo.get("estados");
        idestado = (Integer) ((DBObject) (dbo1.get(dbo1.size() - 1))).get("id");

        gEstado = new Estado();
        switch (idestado + 1) {
        case 1:
            gEstado.setId(1);
            gEstado.setFechaHora(df.format(fecha));
            gEstado.setUsername(username);
            break;
        case 2:
            gEstado.setId(2);
            gEstado.setFechaHora(df.format(fecha));
            gEstado.setUsername(username);
            agregarPedidoDistribuidor(2);
            break;
        case 3:
            gEstado.setId(2);
            gEstado.setFechaHora(df.format(fecha));
            gEstado.setUsername(username);
            agregarPedidoDistribuidor(2);
            break;
        }

        DBObject dbo3 = new BasicDBObject();
        dbo3.put("id", gEstado.getId());
        dbo3.put("fechaHora", gEstado.getFechaHora());
        dbo3.put("username", gEstado.getUsername());
        DBObject dbo4 = new BasicDBObject();
        dbo4.put("estados", dbo3);
        DBObject dbo5 = new BasicDBObject();
        dbo5.put("$push", dbo4);

        coleccion.update(query, dbo5).getN();

        fields = idestado + 1;

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        mongo.close();
    }
    return fields;

}

From source file:dao.CocinaDAO.java

void agregarPedidoDistribuidor(int idPedido) {
    ConexionMLab con = new ConexionMLab();
    MongoClient mongo = con.getConexion();
    try {/*from w  w w .  j  a  v  a2 s .  c o  m*/

        DB db = mongo.getDB("pizzaplaneta");
        DBCollection coleccion = db.getCollection("empleado");
        BasicDBObject query = new BasicDBObject();
        BasicDBObject query1 = new BasicDBObject();
        query1.put("$eq", "dtorres");
        query.put("username", query1);
        DBObject dbo3 = new BasicDBObject();
        dbo3.put("id", idPedido);
        DBObject dbo4 = new BasicDBObject();
        dbo4.put("pedidos", dbo3);
        DBObject dbo5 = new BasicDBObject();
        dbo5.put("$push", dbo4);

        coleccion.update(query, dbo5).getN();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        mongo.close();
    }
}

From source file:dao.component.TrabajadorDAO.java

@Override
public String actualizartrabajador(TrabajadorTO trabajador) {
    String rpta = null;/*from  w w  w  .  j  a v  a2  s.  c  om*/
    DBCollection table = db.getCollection("trabajador");
    // search document where name="mkyong" and update it with new values
    BasicDBObject query = new BasicDBObject();
    query.put("idTrabajador", trabajador.getIdTrabajador());

    BasicDBObject newDocument = new BasicDBObject();
    // newDocument.put("idTrabajador", trabajador.getIdTrabajador());
    newDocument.put("nombre", trabajador.getNombre());
    newDocument.put("genero", trabajador.getGenero());
    newDocument.put("dni", trabajador.getDni());
    newDocument.put("fecha_nac", trabajador.getFecha_nac());
    newDocument.put("estado_civil", trabajador.getEstado_civil());
    newDocument.put("estado", trabajador.getEstado());
    newDocument.put("cuenta", trabajador.getCuenta());
    newDocument.put("seguro_invalidez", trabajador.getSeguro_invalidez());
    newDocument.put("comision", trabajador.getComision());
    newDocument.put("idAFP", trabajador.getIdAFP());
    newDocument.put("idCategoria", trabajador.getIdCategoria());
    newDocument.put("idPuesto", trabajador.getIdPuesto());

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

    table.update(query, updateObj);
    return rpta;
}

From source file:de.fhg.igd.mongomvcc.impl.MongoDBVBranch.java

License:Open Source License

@Override
public long commit() {
    Index idx = getIndex();/* ww w .  j  ava2s  .  c om*/
    //clone dirty objects because we clear them below
    Map<String, IdMap> dos = new HashMap<String, IdMap>(idx.getDirtyObjects());
    Commit head = getHeadCommit();
    Commit c = new Commit(_db.getCounter().getNextId(), head.getCID(), _rootCid, dos);
    _tree.addCommit(c);
    updateHead(c);

    //mark deleted objects as deleted in the database
    DB db = _db.getDB();
    String lifetimeAttr = MongoDBConstants.LIFETIME + "." + getRootCid();
    for (Map.Entry<String, IdSet> e : idx.getDeletedOids().entrySet()) {
        DBCollection dbc = db.getCollection(e.getKey());
        IdSetIterator li = e.getValue().iterator();
        while (li.hasNext()) {
            long oid = li.next();
            //save the CID of the commit where the object has been deleted
            dbc.update(new BasicDBObject(MongoDBConstants.ID, oid),
                    new BasicDBObject("$set", new BasicDBObject(lifetimeAttr, head.getCID())));
        }
    }

    //mark dirty objects as inserted
    String instimeAttr = MongoDBConstants.LIFETIME + ".i" + getRootCid();
    for (Map.Entry<String, IdMap> e : dos.entrySet()) {
        DBCollection dbc = db.getCollection(e.getKey());
        IdMap m = e.getValue();
        IdMapIterator li = m.iterator();
        while (li.hasNext()) {
            li.advance();
            long oid = li.value();
            if (oid == -1) {
                //the document has been inserted and then deleted again
                //do not save time of insertion
                continue;
            }
            //save the CID of the commit where the object has been inserted
            dbc.update(new BasicDBObject(MongoDBConstants.ID, oid),
                    new BasicDBObject("$set", new BasicDBObject(instimeAttr, head.getCID())));
        }
    }

    //reset index
    idx.clearDirtyObjects();

    //if we fail below, the commit has already been performed and the
    //index is clear. failing below simply means the named branch's
    //head could not be updated. If the caller wants to keep the commit
    //he/she just has to create a new named branch based on this
    //branch's head.

    //update named branch's head
    if (_name != null) {
        //synchronize the following part, because we first resolve the branch
        //and then update it
        synchronized (this) {
            //check for conflicts (i.e. if another thread has already updated the branch's head)
            if (_tree.resolveBranch(_name).getCID() != c.getParentCID()) {
                throw new VException("Branch " + _name + " has already been " + "updated by another commit");
            }
            _tree.updateBranchHead(_name, c.getCID());
        }
    }

    return c.getCID();
}

From source file:dsll.pinterest.crawler.Reduce.java

private static Text updatePinContent(String url, DBCollection pinsCollection)
        throws JSONException, IOException {
    // add more related pins, include more boards
    String id = url.split("/pin/")[1];
    DBCursor c = pinsCollection.find(new BasicDBObject("ID", id));
    DBObject oldPin = c.next();/*from ww  w  .  j a  v  a 2 s  .  com*/
    JSONArray oldBoards = new JSONArray(oldPin.get("board").toString());
    JSONArray oldRltPin = new JSONArray(oldPin.get("related_pins").toString());

    Document doc = Jsoup.connect(url).get();
    Element bottomDoc = doc.select("div[class=Module CloseupSidebar]").first();

    //pin board
    Element boardEle = bottomDoc.select("div[class=boardHeader]").first();
    JSONArray board = new JSONArray();
    JSONObject b = new JSONObject();
    String boardName = "";
    try {
        boardName = boardEle.select("h3[class=title]").text().trim();
    } catch (Exception ee) {
    }
    String boardSrc = "";
    try {
        boardSrc = "https://www.pinterest.com" + boardEle.select("a").attr("href").trim();
    } catch (Exception ee) {
    }
    b.append("name", boardName);
    b.append("src", boardSrc);
    board.put(b);

    //related pins
    bottomDoc = doc
            .select("div[class=closeupBottom] div[class=Module CloseupBottom] div[class=relatedPinsWrapper]")
            .first();

    JSONArray relatedPins = new JSONArray();
    Elements relatedPinsConts = bottomDoc.select("div[class=pinWrapper]");
    for (Element relatedPinsCont : relatedPinsConts) {
        JSONObject relatedPin = new JSONObject();
        relatedPin.append("src",
                "https://www.pinterest.com" + relatedPinsCont.select("div[class=pinHolder] > a").attr("href"));
        relatedPins.put(relatedPin);
    }

    // process new boards
    List<String> oldBoardNames = new ArrayList<String>();
    for (int i = 0; i < oldBoards.length(); i++) {
        oldBoardNames.add(oldBoards.getJSONObject(i).getString("name"));
    }
    for (int i = 0; i < board.length(); i++) {
        JSONObject tmp = board.getJSONObject(i);
        if (oldBoardNames.contains(tmp.getString("name"))) {
            continue;
        }
        oldBoards.put(board.get(i));
    }

    // process new related pins
    List<String> oldRelatedPins = new ArrayList<String>();
    for (int i = 0; i < oldRltPin.length(); i++) {
        oldRelatedPins.add(oldRltPin.getJSONObject(i).getString("src"));
    }
    for (int i = 0; i < relatedPins.length(); i++) {
        if (oldRelatedPins.contains(relatedPins.getJSONObject(i).get("src"))) {
            continue;
        }
        oldRltPin.put(relatedPins.getJSONObject(i));
    }

    BasicDBObject newAttr = new BasicDBObject();
    newAttr.append("board", oldBoards);
    newAttr.append("related_pins", oldRltPin);
    BasicDBObject update = new BasicDBObject().append("$set", newAttr);

    pinsCollection.update(new BasicDBObject("ID", id), update);

    return new Text("Pin " + id + " updated.");
}

From source file:dsll.pinterest.crawler.Reduce.java

private static Text updateBoardContent(String url, DBCollection baordsCollection)
        throws JSONException, IOException {
    String id = url.split("/")[4];
    DBCursor c = baordsCollection.find(new BasicDBObject("ID", id));
    DBObject oldPin = c.next();//from  ww w  . ja v  a  2  s .  com
    JSONArray oldPins = new JSONArray(oldPin.get("pins").toString());

    Elements pinsCont = Jsoup.connect(url).get().select("div[class=pinWrapper]");
    // new pins
    JSONArray pins = new JSONArray();
    for (Element pinCont : pinsCont) {
        JSONObject pin = new JSONObject();
        pin.append("src", pinCont.select("div[class=pinHolder]>a").first().attr("href"));
        pins.put(pin);
    }

    List<String> oldPinURL = new ArrayList<String>();
    for (int i = 0; i < oldPins.length(); i++) {
        oldPinURL.add(oldPins.getJSONObject(i).getString("src"));
    }

    for (int i = 0; i < pins.length(); i++) {
        if (oldPinURL.contains(pins.getJSONObject(i).getString("src"))) {
            continue;
        }
        oldPins.put(pins.getJSONObject(i));
    }

    BasicDBObject newAttr = new BasicDBObject();
    newAttr.append("pins", oldPins);
    BasicDBObject update = new BasicDBObject().append("$set", newAttr);

    baordsCollection.update(new BasicDBObject("ID", id), update);
    return new Text("baord " + id + " updated...");
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

private void doUpdate(String collectionName, String guid, BasicDBObject updates)
        throws FailedDBOperationException {
    String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName();
    DBCollection collection = db.getCollection(collectionName);
    BasicDBObject query = new BasicDBObject(primaryKey, guid);
    if (updates.keySet().size() > 0) {
        long startTime = System.currentTimeMillis();
        try {//w w  w. j ava2 s . c  om
            collection.update(query, new BasicDBObject("$set", updates));
        } catch (MongoException e) {
            DatabaseConfig.getLogger().log(Level.SEVERE, "{0} doUpdate failed: {1}",
                    new Object[] { dbName, e.getMessage() });
            throw new FailedDBOperationException(collectionName, updates.toString(),
                    "Original mongo exception:" + e.getMessage());
        }
        DelayProfiler.updateDelay("mongoSetUpdate", startTime);
        long finishTime = System.currentTimeMillis();
        if (finishTime - startTime > 10) {
            DatabaseConfig.getLogger().log(Level.FINE, "{0} Long latency mongoUpdate {1}",
                    new Object[] { dbName, (finishTime - startTime) });
        }
    }
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

@Override
public void removeMapKeys(String collectionName, String name, ColumnField mapField,
        ArrayList<ColumnField> mapKeys) throws FailedDBOperationException {
    String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName();
    DBCollection collection = db.getCollection(collectionName);
    BasicDBObject query = new BasicDBObject(primaryKey, name);

    BasicDBObject updates = new BasicDBObject();

    if (mapField != null && mapKeys != null) {
        for (int i = 0; i < mapKeys.size(); i++) {
            String fieldName = mapField.getName() + "." + mapKeys.get(i).getName();
            updates.append(fieldName, 1);
        }/*from  w w w  .  j  ava 2  s .  com*/
    }
    if (updates.keySet().size() > 0) {
        try {
            DatabaseConfig.getLogger().log(Level.FINE, "{0} <============>unset{1}<============>",
                    new Object[] { dbName, updates.toString() });
            collection.update(query, new BasicDBObject("$unset", updates));
        } catch (MongoException e) {
            DatabaseConfig.getLogger().log(Level.FINE, "{0} removeMapKeys failed: {1}",
                    new Object[] { dbName, e.getMessage() });
            throw new FailedDBOperationException(collectionName, updates.toString(),
                    "Original mongo exception:" + e.getMessage());
        }
    }
}