/** * Modify an existing document. The query parameter employs the same query selectors, as used in {@code find()}. * * @param query the selection criteria for the update * @param update the modifications to apply * @return the result of the operation * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the update command * @throws MongoException if the operation failed for some other reason * @mongodb.driver.manual tutorial/modify-documents/ Modify Documents */ public WriteResult update(final DBObject query, final DBObject update) { return update(query, update, false, false); }
/** * Modify documents in collection. The query parameter employs the same query selectors, as used in {@code find()}. * * @param query the selection criteria for the update * @param update the modifications to apply * @return the result of the operation * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the update command * @throws MongoException if the operation failed for some other reason * @mongodb.driver.manual tutorial/modify-documents/ Modify Documents */ public WriteResult updateMulti(final DBObject query, final DBObject update) { return update(query, update, false, true); }
/** * Modify an existing document or documents in collection. The query parameter employs the same query selectors, as used in {@code * find()}. * * @param query the selection criteria for the update * @param update the modifications to apply * @param upsert when true, inserts a document if no document matches the update query criteria * @param multi when true, updates all documents in the collection that match the update query criteria, otherwise only updates * one * @param aWriteConcern {@code WriteConcern} to be used during operation * @return the result of the operation * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the update command * @throws MongoException if the operation failed for some other reason * @mongodb.driver.manual tutorial/modify-documents/ Modify Documents */ public WriteResult update(final DBObject query, final DBObject update, final boolean upsert, final boolean multi, final WriteConcern aWriteConcern) { return update(query, update, upsert, multi, aWriteConcern, null); }
protected <T extends Persisted> void removeEmbedded(T model, String arrayKey, String key, String searchId) { BasicDBObject aryQry = new BasicDBObject(arrayKey, searchId); BasicDBObject qry = new BasicDBObject("_id", new ObjectId(model.getId())); BasicDBObject update = new BasicDBObject("$pull", new BasicDBObject(key, aryQry)); // http://docs.mongodb.org/manual/reference/operator/pull/ collection(model).update(qry, update); }
protected <T extends Persisted> void removeEmbedded(T model, String key, String searchId) { BasicDBObject aryQry = new BasicDBObject("id", searchId); BasicDBObject qry = new BasicDBObject("_id", new ObjectId(model.getId())); BasicDBObject update = new BasicDBObject("$pull", new BasicDBObject(key, aryQry)); // http://docs.mongodb.org/manual/reference/operator/pull/ collection(model).update(qry, update); }
/** * Modify an existing document or documents in collection. The query parameter employs the same query selectors, as used in {@code * find()}. * * @param query the selection criteria for the update * @param update the modifications to apply * @param upsert when true, inserts a document if no document matches the update query criteria * @param multi when true, updates all documents in the collection that match the update query criteria, otherwise only updates one * @return the result of the operation * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the update command * @throws MongoException if the operation failed for some other reason * @mongodb.driver.manual tutorial/modify-documents/ Modify Documents */ public WriteResult update(final DBObject query, final DBObject update, final boolean upsert, final boolean multi) { return update(query, update, upsert, multi, getWriteConcern()); }
private Optional<String> migrateStream(Stream stream) { final List<AlarmCallbackConfiguration> alarmCallbacks = alarmCallbackService.getForStream(stream); final List<Optional<String>> updatedConfigurations = alarmCallbacks.stream() .filter(callbackConfiguration -> callbackConfiguration.getType().equals(EmailAlarmCallback.class.getCanonicalName())) .map(callbackConfiguration -> this.updateConfiguration(stream, callbackConfiguration)) .collect(Collectors.toList()); if (!updatedConfigurations.stream().allMatch(Optional::isPresent)) { final long errors = updatedConfigurations.stream() .filter(streamId -> !streamId.isPresent()) .count(); LOG.error("Failed moving alert receivers in " + errors + " email alarm callbacks."); return Optional.empty(); } this.dbCollection.update( new BasicDBObject("_id", new ObjectId(stream.getId())), new BasicDBObject("$unset", new BasicDBObject(StreamImpl.FIELD_ALERT_RECEIVERS, "")) ); LOG.debug("Successfully removed alert receivers from stream <" + stream.getId() + ">."); return Optional.of(updatedConfigurations.stream().map(Optional::get).collect(Collectors.joining(", "))); }
@Override public void addOutputs(ObjectId streamId, Collection<ObjectId> outputIds) { final BasicDBList outputs = new BasicDBList(); outputs.addAll(outputIds); collection(StreamImpl.class).update( new BasicDBObject("_id", streamId), new BasicDBObject("$addToSet", new BasicDBObject(StreamImpl.FIELD_OUTPUTS, new BasicDBObject("$each", outputs))) ); clusterEventBus.post(StreamsChangedEvent.create(streamId.toHexString())); }
/** * Modify an existing document or documents in collection. By default the method updates a single document. The query parameter employs * the same query selectors, as used in {@code find()}. * * @param query the selection criteria for the update * @param update the modifications to apply * @param upsert when true, inserts a document if no document matches the update query criteria * @param multi when true, updates all documents in the collection that match the update query criteria, otherwise only updates * one * @param concern {@code WriteConcern} to be used during operation * @param encoder {@code DBEncoder} to be used * @return the result of the operation * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the update command * @throws MongoException if the operation failed for some other reason * @mongodb.driver.manual tutorial/modify-documents/ Modify Documents */ public WriteResult update(final DBObject query, final DBObject update, final boolean upsert, final boolean multi, final WriteConcern concern, @Nullable final DBEncoder encoder) { return update(query, update, upsert, multi, concern, null, encoder); }
protected <T extends Persisted> void embed(T model, String key, EmbeddedPersistable o) throws ValidationException { Map<String, List<ValidationResult>> errors = validate(model.getEmbeddedValidations(key), o.getPersistedFields()); if (!errors.isEmpty()) { throw new ValidationException(errors); } Map<String, Object> fields = Maps.newHashMap(o.getPersistedFields()); fieldTransformations(fields); BasicDBObject dbo = new BasicDBObject(fields); collection(model).update(new BasicDBObject("_id", new ObjectId(model.getId())), new BasicDBObject("$push", new BasicDBObject(key, dbo))); }
@Override public void removeOutputFromAllStreams(Output output) { ObjectId outputId = new ObjectId(output.getId()); DBObject match = new BasicDBObject(StreamImpl.FIELD_OUTPUTS, outputId); DBObject modify = new BasicDBObject("$pull", new BasicDBObject(StreamImpl.FIELD_OUTPUTS, outputId)); // Collect streams that will change before updating them because we don't get the list of changed streams // from the upsert call. final ImmutableSet<String> updatedStreams; try (final DBCursor cursor = collection(StreamImpl.class).find(match)) { updatedStreams = StreamSupport.stream(cursor.spliterator(), false) .map(stream -> stream.get("_id")) .filter(Objects::nonNull) .map(id -> ((ObjectId) id).toHexString()) .collect(ImmutableSet.toImmutableSet()); } collection(StreamImpl.class).update( match, modify, false, true ); clusterEventBus.post(StreamsChangedEvent.create(updatedStreams)); }
@Override public void removeOutput(Stream stream, Output output) { collection(stream).update( new BasicDBObject("_id", new ObjectId(stream.getId())), new BasicDBObject("$pull", new BasicDBObject(StreamImpl.FIELD_OUTPUTS, new ObjectId(output.getId()))) ); clusterEventBus.post(StreamsChangedEvent.create(stream.getId())); }
@Override public void addOutput(Stream stream, Output output) { collection(stream).update( new BasicDBObject("_id", new ObjectId(stream.getId())), new BasicDBObject("$addToSet", new BasicDBObject(StreamImpl.FIELD_OUTPUTS, new ObjectId(output.getId()))) ); clusterEventBus.post(StreamsChangedEvent.create(stream.getId())); }
private WriteResult saveDocument(final DBCollection dbColl, final DBObject document, final InsertOptions options) { if (document.get(ID_FIELD_NAME) == null) { return dbColl.insert(singletonList(document), options.getOptions()); } else { return dbColl.update(new BasicDBObject(ID_FIELD_NAME, document.get(ID_FIELD_NAME)), document, new DBCollectionUpdateOptions() .bypassDocumentValidation(options.getBypassDocumentValidation()) .writeConcern(options.getWriteConcern()) .upsert(true)); } }
@Override public <T extends Persisted> String save(T model) throws ValidationException { Map<String, List<ValidationResult>> errors = validate(model, model.getFields()); if (!errors.isEmpty()) { throw new ValidationException(errors); } BasicDBObject doc = new BasicDBObject(model.getFields()); doc.put("_id", new ObjectId(model.getId())); // ID was created in constructor or taken from original doc already. // Do field transformations fieldTransformations(doc); /* * We are running an upsert. This means that the existing * document will be updated if the ID already exists and * a new document will be created if it doesn't. */ BasicDBObject q = new BasicDBObject("_id", new ObjectId(model.getId())); collection(model).update(q, doc, true, false); return model.getId(); }
@Override public <T> UpdateResults update(final Query<T> query, final UpdateOperations<T> operations, final UpdateOptions options) { DBCollection dbColl = query.getCollection(); // TODO remove this after testing. if (dbColl == null) { dbColl = getCollection(query.getEntityClass()); } final MappedClass mc = getMapper().getMappedClass(query.getEntityClass()); final List<MappedField> fields = mc.getFieldsAnnotatedWith(Version.class); DBObject queryObject = query.getQueryObject(); if (operations.isIsolated()) { queryObject.put("$isolated", true); } if (!fields.isEmpty()) { operations.inc(fields.get(0).getNameToStore(), 1); } final BasicDBObject update = (BasicDBObject) ((UpdateOpsImpl) operations).getOps(); if (LOG.isTraceEnabled()) { LOG.trace(format("Executing update(%s) for query: %s, ops: %s, multi: %s, upsert: %s", dbColl.getName(), queryObject, update, options.isMulti(), options.isUpsert())); } return new UpdateResults(dbColl.update(queryObject, update, enforceWriteConcern(options, query.getEntityClass()) .getOptions())); }
/** * Modify an existing document or documents in collection. By default the method updates a single document. The query parameter employs * the same query selectors, as used in {@link DBCollection#find(DBObject)}. * * @param query the selection criteria for the update * @param update the modifications to apply * @param upsert when true, inserts a document if no document matches the update query criteria * @param multi when true, updates all documents in the collection that match the update query criteria, otherwise only updates one * @param concern {@code WriteConcern} to be used during operation * @param bypassDocumentValidation whether to bypass document validation. * @param encoder the DBEncoder to use * @return the result of the operation * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the update command * @throws MongoException if the operation failed for some other reason * @mongodb.driver.manual tutorial/modify-documents/ Modify * @since 2.14 */ public WriteResult update(final DBObject query, final DBObject update, final boolean upsert, final boolean multi, final WriteConcern concern, @Nullable final Boolean bypassDocumentValidation, @Nullable final DBEncoder encoder) { return update(query, update, new DBCollectionUpdateOptions().upsert(upsert).multi(multi) .writeConcern(concern).bypassDocumentValidation(bypassDocumentValidation).encoder(encoder)); }
return new UpdateResults(dbColl.update(queryObject, update, enforceWriteConcern(options, query.getEntityClass()) .getOptions()));
Mongo m = new Mongo("localhost", 27017); DB db = m.getDB("test"); DBCollection myColl = db.getCollection("myCollection"); BasicDBObject docToInsert = new BasicDBObject("resourceID", "3"); docToInsert.put("resourceName", "Foo Test3"); BasicDBObject updateQuery = new BasicDBObject("_id", "1"); updateQuery.put("itemList.itemID", "1"); BasicDBObject updateCommand = new BasicDBObject("$push", new BasicDBObject("itemList.$.resources", docToInsert)); myColl.update(updateQuery, updateCommand); System.out.println(myColl.findOne().toString());
DB db = conn.getDB( "yourDB" ); DBCollection coll = db.getCollection( "yourCollection" ); ObjectId _id = new ObjectId("4e71b07ff391f2b283be2f95"); ObjectId arrayId = new ObjectId("4e639a918dca838d4575979c"); BasicDBObject query = new BasicDBObject(); query.put("_id", _id); query.put("array._arrayId", arrayId); BasicDBObject data = new BasicDBObject(); data.put("array.$.someField", "updated"); BasicDBObject command = new BasicDBObject(); command.put("$set", data); coll.update(query, command);