List of usage examples for com.mongodb DBCollection update
public WriteResult update(final DBObject query, final DBObject update, final boolean upsert, final boolean multi, final WriteConcern aWriteConcern)
From source file:ch.agent.crnickl.mongodb.WriteMethodsForSchema.java
License:Apache License
/** * Update the basic schema setup in the database. * Throw an exception if the operation cannot be done. * /*from www.jav a 2 s. c om*/ * @param schema a schema * @param policy * @return true if the schema was updated * @throws T2DBException */ public boolean updateSchema(UpdatableSchema schema, SchemaUpdatePolicy policy) throws T2DBException { boolean done = false; Throwable cause = null; Surrogate s = schema.getSurrogate(); MongoDatabase database = (MongoDatabase) s.getDatabase(); try { check(Permission.MODIFY, schema); UpdatableSchema original = database.getReadMethodsForSchema().getSchema(s); Schema base = schema.getBase(); if (base != null && !base.equals(original.getBase())) check(Permission.READ, base); DBCollection coll = getMongoDB(s).getSchemas(); // full replace (no need to set _id in full update) com.mongodb.DBObject operation = mongoObject(MongoDatabase.FLD_SCHEMA_NAME, schema.getName(), MongoDatabase.FLD_SCHEMA_BASE, getIdOrZero(schema.getBase()), MongoDatabase.FLD_SCHEMA_ATTRIBS, attributeDefinitions(schema.getAttributeDefinitions()), MongoDatabase.FLD_SCHEMA_SERIES, seriesDefinitions(schema.getSeriesDefinitions())); coll.update(asQuery(s.getId()), operation, false, false, WriteConcern.SAFE); database.sleep(); try { policy.willUpdate(schema); } catch (T2DBException e) { // Oops! referential integrity broken! operation = mongoObject(MongoDatabase.FLD_SCHEMA_NAME, original.getName(), MongoDatabase.FLD_SCHEMA_BASE, getId(original.getBase()), MongoDatabase.FLD_SCHEMA_ATTRIBS, original.getAttributeDefinitions(), MongoDatabase.FLD_SCHEMA_SERIES, original.getSeriesDefinitions()); coll.update(asQuery(s.getId()), operation); throw e; } done = true; } catch (Exception e) { cause = e; } finally { } if (cause != null) throw T2DBMsg.exception(cause, E.E30122, schema.getName()); return done; }
From source file:ch.agent.crnickl.mongodb.WriteMethodsForValueType.java
License:Apache License
/** * Update a value type in the database.//from ww w . jav a 2 s . c om * Throw an exception if the operation cannot be done. * Updating a value type is an expensive operation, because in case * * @param vt a value type * @param policy a schema udpdating policy * @throws T2DBException */ public <T> void updateValueType(ValueType<T> vt, SchemaUpdatePolicy policy) throws T2DBException { boolean done = false; Throwable cause = null; Surrogate s = vt.getSurrogate(); MongoDatabase database = (MongoDatabase) s.getDatabase(); try { check(Permission.MODIFY, vt); DBCollection coll = getMongoDB(s).getValueTypes(); if (vt.isRestricted() && vt.getValues().size() > 0) { ValueType<T> original = database.getReadMethodsForValueType().getValueType(s); Set<T> deleted = deletedValues(original, vt); com.mongodb.DBObject operation = operation(Operator.SET, MongoDatabase.FLD_VT_NAME, vt.getName(), MongoDatabase.FLD_VT_VALUES, valueDescriptionsAsMap(vt)); if (deleted.size() > 0) { // dangerous update! see comment in MongoDatabase.sleep Iterator<T> it = deleted.iterator(); while (it.hasNext()) { policy.willDelete(vt, it.next()); } coll.update(asQuery(s.getId()), operation, false, false, WriteConcern.SAFE); database.sleep(); try { it = deleted.iterator(); while (it.hasNext()) { policy.willDelete(vt, it.next()); } } catch (T2DBException e) { // restore state and throw exception operation = operation(Operator.SET, MongoDatabase.FLD_VT_NAME, original.getName(), MongoDatabase.FLD_VT_VALUES, valueDescriptionsAsMap(original)); coll.update(asQuery(s.getId()), operation); throw e; } } else { coll.update(asQuery(s.getId()), operation); } } else coll.update(asQuery(s.getId()), operation(Operator.SET, MongoDatabase.FLD_VT_NAME, vt.getName())); done = true; } catch (Exception e) { cause = e; } finally { } if (!done || cause != null) throw T2DBMsg.exception(cause, E.E10146, vt.getName()); }
From source file:com.andreig.jetty.WriteServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPost()"); if (!can_write(req)) { res.sendError(SC_UNAUTHORIZED);//from w w w.ja v a 2s .c om return; } InputStream is = req.getInputStream(); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); if (db_name == null || col_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; col_name = names[1]; } if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } boolean upsert = Boolean.parseBoolean(req.getParameter("upsert")); boolean multi = Boolean.parseBoolean(req.getParameter("multi")); DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); BufferedReader r = null; DBObject q = null, o = null; try { r = new BufferedReader(new InputStreamReader(is)); String q_s = r.readLine(); if (q_s == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } String o_s = r.readLine(); if (o_s == null) { error(res, SC_BAD_REQUEST, Status.get("obj to update missing")); return; } try { q = (DBObject) JSON.parse(q_s); o = (DBObject) JSON.parse(o_s); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } } finally { if (r != null) r.close(); } // // search if (do_search) { String fn = col.getFullName(); DBCursor c = col.find(q); int cnt = c.count(); if (!multi) c.limit(1); long l = multi ? cnt : 1; String toupdate[] = new String[(int) l]; int n = 0; boolean insert = false; if (upsert && !multi && cnt == 0) insert = true; while (c.hasNext()) { DBObject _o = c.next(); ObjectId oid = (ObjectId) _o.get("_id"); String id = oid.toStringMongod(); toupdate[n++] = id; } c.close(); List<String> flds = Config.search_index_fields.get(fn); boolean commit = false; Document doc = null; Search _writer = search.get_writer(); if (flds != null && flds.size() > 0) { doc = new Document(); try { for (String fld : flds) { String val = (String) o.get(fld); if (val == null) continue; Search.add_searchable_s(doc, fld, val); commit = true; } if (commit) _writer.commit(doc); } catch (ClassCastException e) { error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String")); return; } catch (CorruptIndexException e) { error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e)); return; } } if (commit && insert) log.warning("upsert with search not implemented yet"); else _writer.update(toupdate, doc); } WriteResult wr = col.update(q, o, upsert, multi, write_concern); // return operation status if (do_return) { out_str(req, wr.toString()); if (wr.getError() == null) { res.setStatus(SC_BAD_REQUEST); return; } } res.setStatus(SC_CREATED); }
From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doPost()"); if (!can_write(req)) { res.sendError(SC_UNAUTHORIZED);//from w w w . j a v a 2 s . c o m return; } InputStream is = req.getInputStream(); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); if (db_name == null || col_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; col_name = names[1]; } if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } boolean upsert = Boolean.parseBoolean(req.getParameter("upsert")); boolean multi = Boolean.parseBoolean(req.getParameter("multi")); DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); BufferedReader r = null; DBObject q = null, o = null; try { r = new BufferedReader(new InputStreamReader(is)); String q_s = r.readLine(); if (q_s == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } String o_s = r.readLine(); if (o_s == null) { error(res, SC_BAD_REQUEST, Status.get("obj to update missing")); return; } try { q = (DBObject) JSON.parse(q_s); o = (DBObject) JSON.parse(o_s); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } } finally { if (r != null) r.close(); } // // search if (do_search) { String fn = col.getFullName(); DBCursor c = col.find(q); int cnt = c.count(); if (!multi) c.limit(1); long l = multi ? cnt : 1; String toupdate[] = new String[(int) l]; int n = 0; boolean insert = false; if (upsert && !multi && cnt == 0) insert = true; while (c.hasNext()) { DBObject _o = c.next(); ObjectId oid = (ObjectId) _o.get("_id"); String id = oid.toStringMongod(); toupdate[n++] = id; } c.close(); List<String> flds = Config.search_index_fields.get(fn); boolean commit = false; Document doc = null; Search _writer = search.get_writer(); if (flds != null && flds.size() > 0) { doc = new Document(); try { for (String fld : flds) { String val = (String) o.get(fld); if (val == null) continue; _writer.add_searchable_s(doc, fld, val); commit = true; } if (commit) _writer.commit(doc); } catch (ClassCastException e) { error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String")); return; } catch (CorruptIndexException e) { error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e)); return; } } if (commit && insert) log.warn("upsert with search not implemented yet"); else _writer.update(toupdate, doc); } WriteResult wr = col.update(q, o, upsert, multi, write_concern); // return operation status if (do_return) { out_str(req, wr.toString()); if (wr.getError() == null) { res.setStatus(SC_BAD_REQUEST); return; } } res.setStatus(SC_CREATED); }
From source file:com.sfelf.connectors.mongoOplogCursorConnector.java
License:Open Source License
/** * Updates the document with "_id" = namespace in the {@link DBCollection} specified by log setting the field * {@value #LAST_TIMESTAMP_LOG_FIELD} = lastTimestamp if {@link #logLastTimestamp} == true. * /* ww w .j a v a2s .c o m*/ * @param log {@link DBCollection} to update * @param namespace value of the _id field in the document to update * @param lastTimestamp value to assign to the {@value #LAST_TIMESTAMP_LOG_FIELD} field */ private void updateLastTimestampLog(DBCollection log, String namespace, BSONTimestamp lastTimestamp) { if (this.logLastTimestamp) { DBObject query = new BasicDBObject("_id", namespace); DBObject update = new BasicDBObject("$set", new BasicDBObject(LAST_TIMESTAMP_LOG_FIELD, lastTimestamp)); log.update(query, update, true, false, LOG_WRITE_CONCERN); } }
From source file:com.socialsky.mods.MongoPersistor.java
License:Apache License
private void doUpdate(Message<JsonObject> message) { String collection = getMandatoryString("collection", message); if (collection == null) { return;/*from w w w . j a v a 2 s. c om*/ } JsonObject criteriaJson = getMandatoryObject("criteria", message); if (criteriaJson == null) { return; } DBObject criteria = jsonToDBObject(criteriaJson); JsonObject objNewJson = getMandatoryObject("objNew", message); if (objNewJson == null) { return; } DBObject objNew = jsonToDBObject(objNewJson); Boolean upsert = message.body().getBoolean("upsert", false); Boolean multi = message.body().getBoolean("multi", false); DBCollection coll = db.getCollection(collection); WriteConcern writeConcern = WriteConcern.valueOf(getOptionalStringConfig("writeConcern", "")); // Backwards compatibility if (writeConcern == null) { writeConcern = WriteConcern.valueOf(getOptionalStringConfig("write_concern", "")); } if (writeConcern == null) { writeConcern = db.getWriteConcern(); } WriteResult res = coll.update(criteria, objNew, upsert, multi, writeConcern); if (res.getError() == null) { JsonObject reply = new JsonObject(); reply.putNumber("number", res.getN()); sendOK(message, reply); } else { sendError(message, res.getError()); } }
From source file:com.tomtom.speedtools.mongodb.DaoUtils.java
License:Apache License
/** * Update a document in a collection./*from w w w . j a v a2 s . c o m*/ * * @param collection Collection that contains the document. * @param query Query to find the document. * @param update Update for document. * @param updateLastModified True if the last modified time needs to be adjusted as well (to now). * @throws EntityStoreException New document cannot be stored. The error will have been logged. * @throws EntityNotFoundException The document was not found. The error will have been logged. */ public static void update(@Nonnull final DBCollection collection, @Nonnull final MongoDBQuery query, @Nonnull final MongoDBUpdate update, final boolean updateLastModified) throws EntityStoreException, EntityNotFoundException { assert collection != null; assert query != null; assert update != null; try { // Update last modified time. if (updateLastModified) { update.setRaw(MongoDBKeyNames.LAST_MODIFIED_KEY, UTCTime.now().toDate()); } // Make sure upsert is set to false to not create new records on the fly. final WriteResult result = collection.update(query.toDBObject(), update.toDBObject(), NO_UPSERT, NO_MULTI, writeConcern); if (result.getN() == 0) { final String message = "Couldn't find entity to update, query: " + query + ", update: " + update + ", " + "collection: " + collection.getName() + '.'; LOG.error("update: {}", message); throw new EntityNotFoundException(message); } } catch (final MapperException | MongoException e) { final String message = "Couldn't map entity to update, query: " + query + ", update: " + update + ", " + "collection: " + collection.getName() + '.'; LOG.error("update: " + message, e); throw new EntityStoreException(message, e); } }
From source file:com.tomtom.speedtools.mongodb.DaoUtils.java
License:Apache License
/** * Update or insert a document in a collection. * * @param collection Collection that contains the document. * @param query Query to find the document. * @param value Update (or initial value) for document. * @param updateLastModified True if the last modified time needs to be adjusted as well (to now). * @return Number of records updated (0 if inserted, 1 if updated). * @throws EntityStoreException New document cannot be stored. The error will have been logged. *//*from ww w . j ava2 s . co m*/ public static int upsert(@Nonnull final DBCollection collection, @Nonnull final MongoDBQuery query, @Nonnull final DBObject value, final boolean updateLastModified) throws EntityStoreException { assert collection != null; assert query != null; assert value != null; try { // Update last modified time. if (updateLastModified) { value.put(MongoDBKeyNames.LAST_MODIFIED_KEY, UTCTime.now().toDate()); } // Make sure upsert is set to true to create the object if it is not found. final WriteResult result = collection.update(query.toDBObject(), value, UPSERT, NO_MULTI, writeConcern); final int nr = result.getN(); if (nr == 0) { LOG.debug("upsert: Inserted new object, query={}, collection={}", query, collection.getName()); } return nr; } catch (final MapperException | MongoException e) { final String message = "Couldn't map entity to update, query: " + query + ", update: " + value + ", " + "collection: " + collection.getName() + '.'; LOG.error("upsert: " + message, e); throw new EntityStoreException(message, e); } }
From source file:geojson.sof20181050.ConvertToGeoJSON.java
License:Apache License
/** * Performs the document updates using the legacy driver. * <p>// w w w .j av a 2s . com * The main draw back here (other than those discussed in * {@link #doSynchronously()}) is the difficulty creating the GeoJSON * documents. * </p> * * @throws UnknownHostException * On an invalid URI. */ protected static void doLegacy() throws UnknownHostException { // Execute the query to find all of the documents and then // update them. final com.mongodb.MongoClient legacyClient = new com.mongodb.MongoClient(new MongoClientURI(URI)); final com.mongodb.DBCollection legacyCollection = legacyClient.getDB(theCollection.getDatabaseName()) .getCollection(theCollection.getName()); try { int count = 0; for (final DBObject doc : legacyCollection.find()) { final Object id = doc.get("_id"); final Number lat = (Number) doc.get("latitude_deg"); final Number lon = (Number) doc.get("longitude_deg"); final BasicDBObject query = new BasicDBObject(); query.append("_id", id); final ArrayList<Double> coordinates = new ArrayList<>(); coordinates.add(lon.doubleValue()); coordinates.add(lat.doubleValue()); final BasicDBObject geojson = new BasicDBObject("type", "Point"); geojson.append("coordinates", coordinates); final BasicDBObject set = new BasicDBObject("loc", geojson); final BasicDBObject update = new BasicDBObject("$set", set); legacyCollection.update(query, update, /* upsert= */false, /* multi= */false, WriteConcern.ACKNOWLEDGED); count += 1; } System.out.printf("Updated %d documents via the legacy driver.%n", count); } finally { // Always close the client. legacyClient.close(); } }
From source file:in.mtap.iincube.mongoapi.MongoUpdater.java
License:Apache License
public WriteResult execute(WriteConcern writeConcern) { assertArguments();/*from w w w . jav a 2 s . c o m*/ DBCollection collection = collectionFactory.get(); return collection.update(findObject, updateObject, upsert, multi, writeConcern); }