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, final boolean upsert,
        final boolean multi) 

Source Link

Document

Modify an existing document or documents in collection.

Usage

From source file:com.apifest.oauth20.MongoDBManager.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public boolean storeScope(Scope scope) {
    boolean stored = false;
    String id = scope.getScope();
    Gson gson = new Gson();
    String json = gson.toJson(scope);
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = parser.parse(json).getAsJsonObject();
    jsonObj.remove("scope");
    // use scope name as _id
    jsonObj.addProperty(ID_NAME, id);//from  w ww. ja v a 2s. c o m

    try {
        // use ObjectMapper in order to represent expiresIn as integer not as double - 100 instead of 100.00
        Map<String, Object> result = new ObjectMapper().readValue(jsonObj.toString(), Map.class);

        // if scope already exits, updates it, otherwise creates the scope
        BasicDBObject query = new BasicDBObject(ID_NAME, id);
        BasicDBObject newObject = new BasicDBObject(result);
        DBCollection coll = db.getCollection(SCOPE_COLLECTION_NAME);
        coll.update(query, newObject, true, false);
        stored = true;
    } catch (JsonParseException e) {
        log.error("cannot store scope {}", scope.getScope(), e);
    } catch (JsonMappingException e) {
        log.error("cannot store scope {}", scope.getScope(), e);
    } catch (IOException e) {
        log.error("cannot store scope {}", scope.getScope(), e);
    }

    return stored;
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public boolean storeScope(Scope scope) {
    boolean stored = false;
    String id = scope.getScope();
    Gson gson = new Gson();
    String json = gson.toJson(scope);
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = parser.parse(json).getAsJsonObject();
    jsonObj.remove("scope");
    // use scope name as _id
    jsonObj.addProperty(CLIENTS_ID, id);

    try {/*  w  w w  .ja  v  a2 s.  co  m*/
        // use ObjectMapper in order to represent expiresIn as integer not as double - 100 instead of 100.00
        Map<String, Object> result = new ObjectMapper().readValue(jsonObj.toString(), Map.class);

        // if scope already exits, updates it, otherwise creates the scope
        BasicDBObject query = new BasicDBObject(CLIENTS_ID, id);
        BasicDBObject newObject = new BasicDBObject(result);
        DBCollection coll = db.getCollection(SCOPE_COLLECTION_NAME);
        coll.update(query, newObject, true, false);
        stored = true;
    } catch (JsonParseException e) {
        log.error("cannot store scope {}", scope.getScope(), e);
    } catch (JsonMappingException e) {
        log.error("cannot store scope {}", scope.getScope(), e);
    } catch (IOException e) {
        log.error("cannot store scope {}", scope.getScope(), e);
    }

    return stored;
}

From source file:com.cloudbees.gasp.model.MongoConnection.java

License:Apache License

public String newLocation(GeoLocation location) {

    DBCollection locations = getCollection();

    // Search by "name" for existing record
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("name", location.getName());

    // Upsert from GaspLocation object
    DBObject updateExpression = new BasicDBObject();
    updateExpression.put("name", location.getName());
    updateExpression.put("formattedAddress", location.getFormattedAddress());

    // Include Location lat/lng data
    BasicDBObject locObj = new BasicDBObject();
    locObj.put("lng", location.getLocation().getLng());
    locObj.put("lat", location.getLocation().getLat());
    updateExpression.put("location", locObj);

    locations.update(searchQuery, updateExpression, true, false);
    String upsertId = locations.findOne(searchQuery).get("_id").toString();

    if (logger.isDebugEnabled())
        logger.debug("addLocation(): " + upsertId);

    // Return the _id field for the upserted record
    return upsertId;
}

From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java

License:Apache License

public static WriteResult update(PersistenceContext context, MetaClass metadata, DBObject queryObject,
        DBObject bodyObject) {//from www .ja v  a  2s.  c  om
    long start = System.currentTimeMillis();
    WriteResult writeResult = null;
    String msg = "success";
    DBCollection dbCollection = context.getDBCollection(metadata);
    try {
        writeResult = dbCollection.update(queryObject, bodyObject, false, false);
    } catch (Throwable t) {
        msg = t.getMessage();
        handleMongoException(t);
    } finally {
        logMongoAction(context, "update", start, dbCollection, queryObject, bodyObject, null, null, msg);
    }
    return writeResult;
}

From source file:com.ebay.cloud.cms.utils.MongoUtils.java

License:Apache License

public static boolean wrapperUpdate(DBCollection collection, DBObject query, DBObject update) {
    WriteResult wr = collection.update(query, update, false, true);
    Boolean updated = (Boolean) wr.getCachedLastError().get("updatedExisting");
    if (updated == null || !updated) {
        return false;
    }//from   w  w w  . j  a v a2 s  .c  o  m

    return true;
}

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

License:Apache License

public void update(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.upQuery)).getDBObject();
    final BasicDBObject update = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.upUpdate)).getDBObject();
    final boolean upsert = getBooleanFieldValue(Item.upUpsert);
    final boolean multi = getBooleanFieldValue(Item.upMulti);
    final boolean safe = getBooleanFieldValue(Item.upSafe);
    col.setWriteConcern(WriteConcern.SAFE);

    new DbJob() {
        @Override/*from   w w w  .ja  va  2  s . com*/
        public Object doRun() {
            if (safe) {
                long count = col.getCount(query);
                long toupdate = count > 0 ? 1 : 0;
                if (multi) {
                    toupdate = count;
                }
                String text = "Proceed with updating " + toupdate + " of " + count + " documents?";
                ConfirmDialog confirm = new ConfirmDialog(null, "Confirm Update", null, text);
                if (!confirm.show()) {
                    return null;
                }
            }
            return col.update(query, (DBObject) update.copy(), upsert, multi);
        }

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

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

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

        @Override
        public ButtonBase getButton() {
            return button;
        }
    }.addJob();
}

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

License:Apache License

public void doImport(final ButtonBase button) throws IOException {
    ImportDialog dia = UMongo.instance.getGlobalStore().getImportDialog();
    if (!dia.show()) {
        return;/*  w  w  w  . j  a v  a 2s  .  co  m*/
    }
    final boolean dropCollection = dia.getBooleanFieldValue(ImportDialog.Item.dropCollection);
    final boolean continueOnError = dia.getBooleanFieldValue(ImportDialog.Item.continueOnError);
    final boolean upsert = dia.getBooleanFieldValue(ImportDialog.Item.upsert);
    final boolean bulk = dia.getBooleanFieldValue(ImportDialog.Item.bulk);
    String supsertFields = dia.getStringFieldValue(ImportDialog.Item.upsertFields);
    final String[] upsertFields = supsertFields != null ? supsertFields.split(",") : null;
    if (upsertFields != null) {
        for (int i = 0; i < upsertFields.length; ++i) {
            upsertFields[i] = upsertFields[i].trim();
        }
    }
    final DocumentDeserializer dd = dia.getDocumentDeserializer();
    final DBCollection col = getCollectionNode().getCollection();

    new DbJob() {
        @Override
        public Object doRun() throws Exception {
            try {
                if (dropCollection) {
                    col.drop();
                }
                DBObject obj = null;
                List<DBObject> batch = new ArrayList<DBObject>();
                while ((obj = dd.readObject()) != null) {
                    try {
                        if (upsert) {
                            if (upsertFields == null) {
                                col.save(obj);
                            } else {
                                BasicDBObject query = new BasicDBObject();
                                for (int i = 0; i < upsertFields.length; ++i) {
                                    String field = upsertFields[i];
                                    if (!obj.containsField(field)) {
                                        throw new Exception("Upsert field " + field + " not present in object "
                                                + obj.toString());
                                    }
                                    query.put(field, obj.get(field));
                                }
                                col.update(query, obj, true, false);
                            }
                        } else {
                            if (bulk) {
                                if (batch.size() > 1000) {
                                    col.insert(batch);
                                    batch.clear();
                                }
                                batch.add(obj);
                            } else {
                                col.insert(obj);
                            }
                        }
                    } catch (Exception e) {
                        if (continueOnError) {
                            getLogger().log(Level.WARNING, null, e);
                        } else {
                            throw e;
                        }
                    }
                }

                if (!batch.isEmpty()) {
                    col.insert(batch);
                }

            } finally {
                dd.close();
            }
            return null;
        }

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

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

        @Override
        public ButtonBase getButton() {
            return button;
        }
    }.addJob();
}

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

License:Apache License

public void fixCollection(ButtonBase button) {
    final MongoClient m = getCollectionNode().getDbNode().getMongoNode().getMongoClient();
    ArrayList<MongoNode> mongoNodes = UMongo.instance.getMongos();
    String[] mongonames = new String[mongoNodes.size() - 1];
    MongoClient[] mongos = new MongoClient[mongonames.length];
    int i = 0;/* w w w. j  a v a2s  .  c o m*/
    for (MongoNode node : mongoNodes) {
        MongoClient m2 = node.getMongoClient();
        if (m == m2) {
            continue;
        }
        mongonames[i] = m2.toString();
        mongos[i] = m2;
        ++i;
    }
    ComboBox src = (ComboBox) getBoundUnit(Item.fcSrcMongo);
    src.items = mongonames;
    src.structureComponent();
    FormDialog dialog = (FormDialog) getBoundUnit(Item.fcDialog);
    if (!dialog.show()) {
        return;
    }

    final DBCollection dstCol = getCollectionNode().getCollection();
    final MongoClient srcMongo = mongos[src.getIntValue()];
    final boolean upsert = getBooleanFieldValue(Item.fcUpsert);

    final String dbname = dstCol.getDB().getName();
    final String colname = dstCol.getName();
    final DBCollection srcCol = srcMongo.getDB(dbname).getCollection(colname);
    String txt = "About to copy from ";
    txt += srcMongo.getConnectPoint() + "(" + srcCol.count() + ")";
    txt += " to ";
    txt += m.getConnectPoint() + "(" + dstCol.count() + ")";
    if (!new ConfirmDialog(null, "Confirm Fix Collection", null, txt).show()) {
        return;
    }

    new DbJob() {
        @Override
        public Object doRun() {
            DBCursor cur = srcCol.find();
            int count = 0;
            int dup = 0;
            while (cur.hasNext()) {
                DBObject obj = cur.next();
                if (upsert) {
                    BasicDBObject id = new BasicDBObject("_id", obj.get("_id"));
                    dstCol.update(id, obj, true, false);
                } else {
                    try {
                        dstCol.insert(obj);
                    } catch (DuplicateKey e) {
                        // dup keys are expected here
                        ++dup;
                    }
                }
                ++count;
            }
            DBObject res = new BasicDBObject("count", count);
            res.put("dups", dup);
            return res;
        }

        @Override
        public String getNS() {
            return "*";
        }

        @Override
        public String getShortName() {
            return "Fix Collection";
        }
    }.addJob();
}

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

License:Apache License

public void setValue(ButtonBase button) {
    final DocView dv = (DocView) (UMongo.instance.getTabbedResult().getSelectedUnit());
    if (dv.getDBCursor() == null) {
        // local data
        new InfoDialog(null, null, null, "Cannot do in-place update on local data.").show();
        return;/*from   ww w. j a  va 2 s . c  o m*/
    }

    TreeNodeDocumentField field = (TreeNodeDocumentField) dv.getSelectedNode().getUserObject();
    DBObject doc = dv.getSelectedDocument();
    String path = dv.getSelectedDocumentPath();
    Object newValue = UMongo.instance.getGlobalStore().editValue(field.getKey(), field.getValue());

    if (newValue == null) {
        //            new InfoDialog(null, null, null, "Cannot edit this type of data.").show();
        return;
    }

    final DBObject query = doc.containsField("_id") ? new BasicDBObject("_id", doc.get("_id")) : doc;
    DBObject setValue = new BasicDBObject(path, newValue);
    final DBObject update = new BasicDBObject("$set", setValue);

    final DBCollection col = dv.getDBCursor().getCollection();
    new DbJob() {

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

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

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

        @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);
            dv.refresh(null);
        }
    }.addJob();
}

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

License:Apache License

public void unsetValue(ButtonBase button) {
    final DocView dv = (DocView) (UMongo.instance.getTabbedResult().getSelectedUnit());
    DBObject doc = dv.getSelectedDocument();
    String path = dv.getSelectedDocumentPath();

    if (dv.getDBCursor() == null) {
        // local data
        new InfoDialog(null, null, null, "Cannot do in-place update on local data.").show();
        return;/*from   w w w  .j  av  a 2s .  c  om*/
    }

    if (!UMongo.instance.getGlobalStore().confirmDataLossOperation())
        return;

    final DBObject query = doc.containsField("_id") ? new BasicDBObject("_id", doc.get("_id")) : doc;
    DBObject setValue = new BasicDBObject(path, 1);
    final DBObject update = new BasicDBObject("$unset", setValue);

    final DBCollection col = dv.getDBCursor().getCollection();
    new DbJob() {

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

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

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

        @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);
            dv.refresh(null);
        }
    }.addJob();
}