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.caci.dummyserver.MongoRepository.java

public void updateObject(String table, Collection<Pair<String, String>> keys, String json) {
    DB db = mongo.getDB("Objects");
    DBCollection col = db.getCollection(table);

    DBObject queryObject = makeQueryObject(keys, null);
    DBObject updateObject = new BasicDBObject();
    updateObject.put("$set", makeDBObject(keys, json));

    col.update(queryObject, updateObject);
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static String actualizarRecibo(Integer idMetodoPago, String descripcion, Integer cuotas, float precio,
        Integer idReserva) {//w ww  .  j  av  a2 s . c  o m
    String reciboActualizar = null;
    try {
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

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

        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("idMetodoPago", idMetodoPago);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {
            DBObject updateDocument = cursor.next();
            updateDocument.put("descripcion", descripcion);
            updateDocument.put("cuotas", cuotas);
            updateDocument.put("precio", precio);
            updateDocument.put("idReserva", idReserva);
            coll.update(whereQuery, updateDocument);
        }
        System.out.println("Document updated successfully");
        reciboActualizar = "Success";
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (reciboActualizar != null) {
        return "El recibo se ha actualizado correctamente!";
    } else {
        return "El recibo no se ha actualizado!";
    }
}

From source file:com.deliveronthego.DbConnection.java

public String location(String date, double transitionLatitude, double transitionLongitude, double stopLatitude,
        double stopLongitude, String driverId) {
    mongoclient = getConnection();/*  w  w w. jav a  2 s.  c  om*/
    @SuppressWarnings("deprecation")
    DB db = mongoclient.getDB("deliveronthego");
    DBCollection location = db.getCollection("location");
    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("driverID", driverId);
    DBCursor locationCursor = location.find(whereQuery);
    boolean updateFlag = false;

    while (locationCursor.hasNext()) {
        locationCursor.next();
        DBObject locDB = locationCursor.curr();
        System.out.println(locDB);
        String dateStr = locDB.get("Date").toString();
        if (dateStr.equals(date)) {
            location.update(new BasicDBObject("driverID", driverId),
                    new BasicDBObject("$set", new BasicDBObject("transitionLatitude", transitionLatitude)
                            .append("transitionLongitude", transitionLongitude)));
            Double previousStopLatitude = (Double) locDB.get("stopLatitude");
            Double previousStopLongitude = (Double) locDB.get("stopLongitude");
            System.out.println("previousStopLatitude: " + previousStopLatitude);
            System.out.println("previousStopLongitude: " + previousStopLongitude);
            /*if((previousStopLatitude==0.0) && (previousStopLongitude==0.0))
            {
               location.update(new BasicDBObject("driverID", driverId), new BasicDBObject("$set", new BasicDBObject("stopLatitude", stopLatitude).append("stopLongitude", stopLongitude)));
            }*/
        }
        updateFlag = true;
    }

    if (!updateFlag) {
        BasicDBObject locationObj = new BasicDBObject("Date", date.toString())
                .append("transitionLatitude", transitionLatitude)
                .append("transitionLongitude", transitionLongitude).append("stopLatitude", stopLatitude)
                .append("stopLongitude", stopLongitude).append("driverID", driverId);
        location.insert(locationObj);
        return "Location Details Inserted Sucessfully";
    } else {
        return "Location Details Updated";
    }

}

From source file:com.deliveronthego.DbConnection.java

public String transcationNotification(String driverID, Boolean pickedUp, Boolean delivered) {
    mongoclient = getConnection();/*from   w  w  w .j av  a  2  s.com*/
    @SuppressWarnings("deprecation")
    DB db = mongoclient.getDB("deliveronthego");
    DBCollection notification = db.getCollection("notification");

    BasicDBObject notificationObj = new BasicDBObject();
    notificationObj.append("driverID", driverID);
    Date date = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    DBCursor notificationCursor = notification.find(notificationObj);

    if (pickedUp && !delivered) {
        notificationObj.append("pickedUp", pickedUp.toString()).append("delivered", delivered.toString())
                .append("date", cal.toString());
        notification.insert(notificationObj);

        return "New Transaction Data inserted";
    } else {
        if (notificationCursor.hasNext()) {
            notificationCursor.next();
            DBObject notifyObj = notificationCursor.curr();
            Date currentDateInDatabase = (Date) notifyObj.get("date");
            if (!(boolean) notifyObj.get("delivered") && currentDateInDatabase.before(date)) {
                notification.update(new BasicDBObject("driverID", driverID),
                        new BasicDBObject("$set", new BasicDBObject("delivered", delivered.toString())));
                return "Transaction Completed";
            } else {
                return "Transaction failed to update";
            }
        } else {
            return "Transaction failed";
        }
    }
}

From source file:com.ebay.cloud.cms.config.CMSProperties.java

License:Apache License

public void updateConfig(Map<String, Object> configs) {
    DBCollection coll = getPropertiesCollection(ds.getMongoInstance());
    DBCursor cursor = coll.find();//from   w  w  w .j a v a 2s  . c  o m
    // update existing
    while (cursor.hasNext()) {
        BasicDBObject dbo = (BasicDBObject) cursor.next();
        String key = getKey(dbo);
        if (!configs.containsKey(key)) {
            continue;
        }

        BasicDBObject qObject = new BasicDBObject();
        BasicDBObject vObject = new BasicDBObject();
        qObject.append("_id", dbo.get("_id"));
        vObject.append(key, configs.get(key));

        coll.update(qObject, vObject);
        configs.remove(key);
    }

    // insert new config
    if (!configs.isEmpty()) {
        List<DBObject> list = new ArrayList<DBObject>();
        for (Entry<String, Object> entry : configs.entrySet()) {
            DBObject dbo = new BasicDBObject();
            dbo.put(entry.getKey(), entry.getValue());

            list.add(dbo);
        }
        coll.insert(list);
    }

    loadProperties(ds.getMongoInstance());
}

From source file:com.edgytech.umongo.ReplSetPanel.java

License:Apache License

public void addTag(ButtonBase button) {
    final DB config = ((RouterNode) getReplSetNode().getParentNode()).getMongoClient().getDB("config");
    final DBCollection col = config.getCollection("shards");

    ((DynamicComboBox) getBoundUnit(Item.atTag)).items = TagRangeDialog.getExistingTags(config);
    FormDialog dia = (FormDialog) button.getDialog();
    if (!dia.show())
        return;//from  ww  w .  j  a  v a2  s.  c om
    final String tag = getStringFieldValue(Item.atTag);
    final DBObject query = new BasicDBObject("_id", getReplSetNode().getShardName());
    final DBObject update = new BasicDBObject("$addToSet", new BasicDBObject("tags", tag));

    new DbJob() {

        @Override
        public Object doRun() {
            return col.update(query, update);
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Add Tag";
        }

        @Override
        public DBObject getRoot(Object result) {
            BasicDBObject obj = new BasicDBObject("query", query);
            obj.put("update", update);
            return obj;
        }

        @Override
        public void wrapUp(Object res) {
            super.wrapUp(res);
            refreshTagList();
        }
    }.addJob();
}

From source file:com.edgytech.umongo.ReplSetPanel.java

License:Apache License

public void removeTag(ButtonBase button) {
    final DB db = ((RouterNode) getReplSetNode().getParentNode()).getMongoClient().getDB("config");
    final DBCollection col = db.getCollection("shards");
    final String tag = getComponentStringFieldValue(Item.tagList);
    if (tag == null)
        return;/*from   www  .java2 s  . c o m*/

    final DBObject query = new BasicDBObject("_id", getReplSetNode().getShardName());
    final DBObject update = new BasicDBObject("$pull", new BasicDBObject("tags", tag));

    new DbJob() {

        @Override
        public Object doRun() {
            return col.update(query, update);
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Remove Tag";
        }

        @Override
        public DBObject getRoot(Object result) {
            BasicDBObject obj = new BasicDBObject("query", query);
            obj.put("update", update);
            return obj;
        }

        @Override
        public void wrapUp(Object res) {
            super.wrapUp(res);
            refreshTagList();
        }
    }.addJob();
}

From source file:com.emuneee.camerasyncmanager.util.DatabaseUtil.java

License:Apache License

/**
 * Updates a list cameras/*from  www.  j  av  a 2  s .  co m*/
 * @param cameras
 * @return
 */
public boolean updateCameras(List<Camera> cameras) {
    sLogger.info("Updating " + cameras.size() + " cameras");
    boolean result = false;
    DB db = getDatabase();

    try {
        DBCollection collection = db.getCollection("camera");

        for (Camera camera : cameras) {
            BasicDBObject query = new BasicDBObject("_id", camera.getId());
            BasicDBObject dbObj = cameraToDBObject(camera);
            dbObj.append("updated", new Date());
            sLogger.debug("Updating: " + dbObj.toString());
            collection.update(query, dbObj);
            result = true;
        }
    } catch (Exception e) {
        sLogger.error("Exception inserting cameras");
        sLogger.error(e);
    }

    return result;
}

From source file:com.epam.dlab.migration.mongo.changelog.DlabChangeLog.java

License:Apache License

@SuppressWarnings("unchecked")
private void updateSchedulerFieldsForExploratory(DBCollection userInstances, DBObject dbObject) {
    updateSchedulerFields(dbObject);//  ww  w  .  j  a  va  2s.c  o  m
    Optional.ofNullable(dbObject.get("computational_resources")).map(cr -> (List<DBObject>) cr)
            .ifPresent(computationalResources -> computationalResources.forEach(this::updateSchedulerFields));
    userInstances.update(new BasicDBObject(ID, dbObject.get(ID)), dbObject);
}

From source file:com.foodtruckdata.mongodb.UsersInput.java

@Override
public void AddSchedule(Date dateTime, String address, String truck_id) {
    //remove all outdated schedules
    BasicDBObject filter = new BasicDBObject("_id", new ObjectId(truck_id));
    DBCollection coll = mongoDB.getCollection("Trucks");
    Cursor cursor = coll.find(filter);
    if (cursor.hasNext()) {
        BasicDBObject truck = (BasicDBObject) cursor.next();
        BasicDBObject[] schedules = (BasicDBObject[]) truck.get("Schedules");
        for (BasicDBObject schedule : schedules) {
            if (((Date) schedule.get("Time")).compareTo(new Date()) < 0) {
                coll.update(filter, (new BasicDBObject("$pull", (new BasicDBObject("Schedules", schedule)))));
            }//from w w  w.  j a va  2s  .  com
        }
    }
    //insert the new schedule
    if (dateTime.compareTo((new Date())) > 0) {
        BasicDBObject schedule = new BasicDBObject();
        schedule.put("Time", dateTime);
        schedule.put("Address", address);
        //put lat long also
        coll.update(filter, (new BasicDBObject("$addToSet", (new BasicDBObject("Schedules", schedule)))));
    }
}