com.mongodb.client.model.UpdateOptions Java Examples

The following examples show how to use com.mongodb.client.model.UpdateOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongoDB.java    From aion with MIT License 7 votes vote down vote up
/**
 * Adds a new edit to the batch
 *
 * @param key the key to write
 * @param value the value to write. Null indicates we should delete this key
 * @return this
 */
public WriteBatch addEdit(byte[] key, byte[] value) {
    if (value == null) {
        DeleteOneModel deleteModel =
                new DeleteOneModel<>(eq(MongoConstants.ID_FIELD_NAME, new BsonBinary(key)));

        edits.add(deleteModel);
    } else {
        UpdateOneModel updateModel =
                new UpdateOneModel<>(
                        eq(MongoConstants.ID_FIELD_NAME, new BsonBinary(key)),
                        Updates.set(MongoConstants.VALUE_FIELD_NAME, new BsonBinary(value)),
                        new UpdateOptions().upsert(true));

        edits.add(updateModel);
    }

    return this;
}
 
Example #2
Source File: MongoFile.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public static void storeBlock(MongoBlock mongoBlock) {
	// System.out.println("Store: " + mongoBlock.getBlockNumber());

	MongoCollection<Document> c = mongoBlock.mongoFile.mongoDirectory.getBlocksCollection();

	Document query = new Document();
	query.put(MongoDirectory.FILE_NUMBER, mongoBlock.mongoFile.fileNumber);
	query.put(MongoDirectory.BLOCK_NUMBER, mongoBlock.blockNumber);

	Document object = new Document();
	object.put(MongoDirectory.FILE_NUMBER, mongoBlock.mongoFile.fileNumber);
	object.put(MongoDirectory.BLOCK_NUMBER, mongoBlock.blockNumber);
	object.put(MongoDirectory.BYTES, new Binary(mongoBlock.bytes));

	c.replaceOne(query, object, new UpdateOptions().upsert(true));

}
 
Example #3
Source File: MongoNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * create until parent folder if not exists.
 *
 * @param splitPath path to completed.
 * @return direct parent folder id
 */
private String completeFolder(String[] splitPath) {
  String pId = "0";
  for (String currentPath : splitPath) {
    Document query = new Document(Fields.PID, pId)
        .append(Fields.IS_DIR, true)
        .append(Fields.NAME, currentPath);

    String cId = new ObjectId().toString();
    Document doc = new Document("$setOnInsert",
        new Document(Fields.ID, cId)
            .append(Fields.PID, pId)
            .append(Fields.IS_DIR, true)
            .append(Fields.NAME, currentPath));

    Document exist = folders.find(query).first();
    if (exist == null) {
      folders.updateOne(query, doc, new UpdateOptions().upsert(true));
      pId = cId;
    } else {
      pId = exist.getString(Fields.ID);
    }
  }

  return pId;
}
 
Example #4
Source File: DBUser.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private Mono<UpdateResult> updateAchievement(int achievements) {
    // If the achievement is already in this state, no need to request an update
    if (this.getBean().getAchievements() == achievements) {
        LOGGER.debug("[DBUser {}] Achievements update useless, aborting: {}",
                this.getId().asLong(), achievements);
        return Mono.empty();
    }

    LOGGER.debug("[DBUser {}] Achievements update: {}", this.getId().asLong(), achievements);

    return Mono.from(DatabaseManager.getUsers()
            .getCollection()
            .updateOne(
                    Filters.eq("_id", this.getId().asString()),
                    Updates.set("achievements", achievements),
                    new UpdateOptions().upsert(true)))
            .doOnNext(result -> LOGGER.trace("[DBUser {}] Achievements update result: {}",
                    this.getId().asLong(), result))
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(UsersCollection.NAME).inc());
}
 
Example #5
Source File: MongoBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 6 votes vote down vote up
private void insertContextDataAggregatedForResoultion(String dbName, String collectionName,
        GregorianCalendar calendar, String entityId, String entityType, String attrName, String attrType,
        double max, double min, double sum, double sum2, int numSamples, Resolution resolution) {
    // Get database and collection
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);

    // Build the query
    BasicDBObject query = buildQueryForInsertAggregated(calendar, entityId, entityType, attrName, resolution);

    // Prepopulate if needed
    BasicDBObject insert = buildInsertForPrepopulate(attrType, resolution, true);
    UpdateResult res = collection.updateOne(query, insert, new UpdateOptions().upsert(true));

    if (res.getMatchedCount() == 0) {
        LOGGER.debug("Prepopulating data, database=" + dbName + ", collection=" + collectionName + ", query="
                + query.toString() + ", insert=" + insert.toString());
    } // if

    // Do the update
    BasicDBObject update = buildUpdateForUpdate(attrType, calendar, max, min, sum, sum2, numSamples);
    LOGGER.debug("Updating data, database=" + dbName + ", collection=" + collectionName + ", query="
            + query.toString() + ", update=" + update.toString());
    collection.updateOne(query, update);
}
 
Example #6
Source File: Repositories.java    From immutables with Apache License 2.0 6 votes vote down vote up
protected final FluentFuture<Integer> doUpsert(
    final Constraints.ConstraintHost criteria,
    final T document) {
  checkNotNull(criteria, "criteria");
  checkNotNull(document, "document");
  return submit(new Callable<Integer>() {
    @Override
    public Integer call() {
      collection().replaceOne(convertToBson(criteria), document, new UpdateOptions().upsert(true));
      // upsert will always return 1:
      // if document doesn't exists, it will be inserted (modCount == 1)
      // if document exists, it will be updated (modCount == 1)

      return 1;
    }
  });
}
 
Example #7
Source File: ReactiveMongoClientTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private Uni<Document> upsertDoc(String collection, Document docToInsert,
        Document insertStatement,
        String expectedId) {
    return client.getDatabase(DATABASE).getCollection(collection)
            .updateMany(eq("foo", docToInsert.getString("foo")),
                    insertStatement,
                    new UpdateOptions().upsert(true))
            .onItem().produceUni(result -> {
                assertThat(result.getModifiedCount()).isEqualTo(0);
                if (expectedId == null) {
                    assertThat(0).isEqualTo(result.getMatchedCount());
                    assertThat(result.getUpsertedId()).isNotNull();
                } else {
                    assertThat(1).isEqualTo(result.getMatchedCount());
                    assertThat(result.getUpsertedId()).isNull();
                }

                return client.getDatabase(DATABASE).getCollection(collection).find().collectItems().first();
            });
}
 
Example #8
Source File: LumongoIndex.java    From lumongo with Apache License 2.0 6 votes vote down vote up
private void storeIndexSettings() {
	indexLock.writeLock().lock();
	try {
		MongoDatabase db = mongo.getDatabase(mongoConfig.getDatabaseName());
		MongoCollection<Document> dbCollection = db.getCollection(indexConfig.getIndexName() + CONFIG_SUFFIX);
		Document settings = IndexConfigUtil.toDocument(indexConfig);
		settings.put(MongoConstants.StandardFields._ID, SETTINGS_ID);

		Document query = new Document();
		query.put(MongoConstants.StandardFields._ID, SETTINGS_ID);

		dbCollection.replaceOne(query, settings, new UpdateOptions().upsert(true));
	}
	finally {
		indexLock.writeLock().unlock();
	}

}
 
Example #9
Source File: ChronoElement.java    From epcis with Apache License 2.0 6 votes vote down vote up
/**
 * Un-assigns a key/value property from the element. The object value of the
 * removed property is returned.
 *
 * @param key the key of the property to remove from the element
 * @return the object value associated with that key prior to removal. Should be
 *         instance of BsonValue
 */
@Override
public <T> T removeProperty(final String key) {
	try {
		BsonValue value = getProperty(key);
		BsonDocument filter = new BsonDocument();
		filter.put(Tokens.ID, new BsonString(this.id));
		BsonDocument update = new BsonDocument();
		update.put("$unset", new BsonDocument(key, new BsonNull()));
		if (this instanceof ChronoVertex) {
			graph.getVertexCollection().updateOne(filter, update, new UpdateOptions().upsert(true));
			return (T) value;
		} else {
			graph.getEdgeCollection().updateOne(filter, update, new UpdateOptions().upsert(true));
			return (T) value;
		}
	} catch (MongoWriteException e) {
		throw e;
	}
}
 
Example #10
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 6 votes vote down vote up
@Override
public void storeSourceDocument(String uniqueId, long timeStamp, Document document, List<Metadata> metaDataList) throws Exception {
	MongoDatabase db = mongoClient.getDatabase(database);
	MongoCollection<Document> coll = db.getCollection(rawCollectionName);
	Document mongoDocument = new Document();
	mongoDocument.putAll(document);

	if (!metaDataList.isEmpty()) {
		Document metadataMongoDoc = new Document();
		for (Metadata meta : metaDataList) {
			metadataMongoDoc.put(meta.getKey(), meta.getValue());
		}
		mongoDocument.put(METADATA, metadataMongoDoc);
	}

	mongoDocument.put(TIMESTAMP, timeStamp);
	mongoDocument.put(MongoConstants.StandardFields._ID, uniqueId);

	Document query = new Document(MongoConstants.StandardFields._ID, uniqueId);

	coll.replaceOne(query, mongoDocument, new UpdateOptions().upsert(true));
}
 
Example #11
Source File: MongoDbStore.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
public void putAccount(AccountData account) {

  BasicDBObject object = new BasicDBObject("_id", account.getId().getAddress());

  if (account.isHuman()) {
    object.put(ACCOUNT_HUMAN_DATA_FIELD, humanToObject(account.asHuman()));
  } else if (account.isRobot()) {
    object.put(ACCOUNT_ROBOT_DATA_FIELD, robotToObject(account.asRobot()));
  } else {
    throw new IllegalStateException("Account is neither a human nor a robot");
  }

  getAccountCollection().replaceOne(
      filterAccountBy(account.getId()),
      object,
      new UpdateOptions().upsert(true));
}
 
Example #12
Source File: Repositories.java    From immutables with Apache License 2.0 6 votes vote down vote up
protected final FluentFuture<Integer> doUpdate(
        final Constraints.ConstraintHost criteria,
        final Constraints.Constraint update,
        final UpdateOptions options) {

  checkNotNull(criteria, "criteria");
  checkNotNull(update, "update");
  checkNotNull(options, "options");

  return submit(new Callable<UpdateResult>() {
    @Override
    public UpdateResult call() {
      return collection()
          .updateMany(
          convertToBson(criteria),
          convertToBson(update),
          options);
    }
  }).lazyTransform(new Function<UpdateResult, Integer>() {
    @Override
    public Integer apply(UpdateResult input) {
      return (int) input.getModifiedCount();
    }
  });
}
 
Example #13
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 5 votes vote down vote up
private <T> OpResult addOrReplace(MongoCollection<Document> collection, T t) {
    BsonDocument filter = new BsonDocument();
    if (t instanceof StreamDefinition) {
        filter.append("streamId", new BsonString(MetadataUtils.getKey(t)));
    } else if (t instanceof AlertPublishEvent) {
        filter.append("alertId", new BsonString(MetadataUtils.getKey(t)));
    } else {
        filter.append("name", new BsonString(MetadataUtils.getKey(t)));
    }

    String json = "";
    OpResult result = new OpResult();
    try {
        json = mapper.writeValueAsString(t);
        UpdateOptions options = new UpdateOptions();
        options.upsert(true);
        UpdateResult ur = collection.replaceOne(filter, Document.parse(json), options);
        // FIXME: could based on matched count do better matching...
        if (ur.getModifiedCount() > 0 || ur.getUpsertedId() != null) {
            result.code = 200;
            result.message = String.format("update %d configuration item.", ur.getModifiedCount());
        } else {
            result.code = 500;
            result.message = "no configuration item create/updated.";
        }
    } catch (Exception e) {
        result.code = 500;
        result.message = e.getMessage();
        LOG.error("", e);
    }
    return result;
}
 
Example #14
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<UpdateResult> updateMany(final Bson filter, final Bson update, final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.updateMany(filter, update, options, callback);
                }
            }));
}
 
Example #15
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public Publisher<UpdateResult> replaceOne(final Bson filter, final TDocument replacement, final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @SuppressWarnings("deprecation")
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.replaceOne(filter, replacement, options, callback);
                }
            }));
}
 
Example #16
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<UpdateResult> updateOne(final ClientSession clientSession, final Bson filter, final Bson update,
                                         final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.updateOne(clientSession.getWrapped(), filter, update, options, callback);
                }
            }));
}
 
Example #17
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public Publisher<UpdateResult> replaceOne(final ClientSession clientSession, final Bson filter, final TDocument replacement,
                                          final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @SuppressWarnings("deprecation")
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.replaceOne(clientSession.getWrapped(), filter, replacement, options, callback);
                }
            }));
}
 
Example #18
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<UpdateResult> updateOne(final ClientSession clientSession, final Bson filter, final List<? extends Bson> update,
                                         final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.updateOne(clientSession.getWrapped(), filter, update, options, callback);
                }
            }));
}
 
Example #19
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<UpdateResult> updateMany(final Bson filter, final List<? extends Bson> update, final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.updateMany(filter, update, options, callback);
                }
            }));
}
 
Example #20
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<UpdateResult> updateMany(final ClientSession clientSession, final Bson filter, final List<? extends Bson> update,
                                          final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.updateMany(clientSession.getWrapped(), filter, update, options, callback);
                }
            }));
}
 
Example #21
Source File: MongoCollectionUpdate.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase db = getMongoDatabase( _session, argStruct );

	String collection = getNamedStringParam( argStruct, "collection", null );
	if ( collection == null )
		throwException( _session, "please specify a collection" );

	cfData data = getNamedParam( argStruct, "data", null );
	if ( data == null )
		throwException( _session, "please specify data to update" );

	cfData query = getNamedParam( argStruct, "query", null );
	if ( query == null )
		throwException( _session, "please specify query to update" );

	boolean upsert = getNamedBooleanParam( argStruct, "upsert", false );
	boolean multi = getNamedBooleanParam( argStruct, "multi", false );

	try {

		MongoCollection<Document> col = db.getCollection( collection );
		Document qry = getDocument( query );
		Document dat = getDocument( data );
		long start = System.currentTimeMillis();

		if ( multi )
			col.updateMany( qry, dat, new UpdateOptions().upsert( upsert ) );
		else
			col.updateOne( qry, dat, new UpdateOptions().upsert( upsert ) );

		_session.getDebugRecorder().execMongo( col, "update", qry, System.currentTimeMillis() - start );

		return cfBooleanData.TRUE;

	} catch ( MongoException me ) {
		throwException( _session, me.getMessage() );
		return null;
	}
}
 
Example #22
Source File: MongoDbStore.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public void putSignerInfo(ProtocolSignerInfo protocolSignerInfo) throws SignatureException {
  SignerInfo signerInfo = new SignerInfo(protocolSignerInfo);
  byte[] signerId = signerInfo.getSignerId();

  // Not using a modifier here because rebuilding the object is not a lot of
  // work.
  BasicDBObject signerInfoDBObject = new BasicDBObject("_id", signerId);
  signerInfoDBObject.put("protoBuff", protocolSignerInfo.toByteArray());

  getSignerInfoCollection().replaceOne(filterSignerInfoBy(signerId), signerInfoDBObject,
      new UpdateOptions().upsert(true));
}
 
Example #23
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<UpdateResult> updateMany(final ClientSession clientSession, final Bson filter, final Bson update,
                                          final UpdateOptions options) {
    return new ObservableToPublisher<UpdateResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<UpdateResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<UpdateResult> callback) {
                    wrapped.updateMany(clientSession.getWrapped(), filter, update, options, callback);
                }
            }));
}
 
Example #24
Source File: MongoCollectionImpl.java    From mongo-java-driver-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<UpdateResult> replaceOne(final Bson filter, final TDocument replacement, final UpdateOptions options) {
    return RxObservables.create(Observables.observe(new Block<SingleResultCallback<UpdateResult>>() {
        @Override
        public void apply(final SingleResultCallback<UpdateResult> callback) {
            wrapped.replaceOne(filter, replacement, options, callback);
        }
    }), observableAdapter);
}
 
Example #25
Source File: ChronoElement.java    From epcis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public void setProperties(final BsonDocument properties) {
	if (properties == null)
		return;
	BsonDocument filter = new BsonDocument();
	filter.put(Tokens.ID, new BsonString(this.id));
	if (this instanceof ChronoVertex) {
		graph.getVertexCollection().replaceOne(filter, Converter.makeVertexDocument(properties, this.id),
				new UpdateOptions().upsert(true));
	} else {
		ChronoEdge ce = (ChronoEdge) this;
		graph.getEdgeCollection().replaceOne(filter, Converter.makeEdgeDocument(properties, this.id,
				ce.getOutVertex().id, ce.getInVertex().id, ce.getLabel()), new UpdateOptions().upsert(true));
	}
}
 
Example #26
Source File: PermissionStore.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public void updatePermissions(String resourceId, Permissions permissions) throws IResourceStore.ResourceStoreException {
    String jsonPermissions = serialize(permissions);
    Document permissionsDocument = Document.parse(jsonPermissions);

    permissionsDocument.put("_id", new ObjectId(resourceId));

    collection.updateOne(new Document("_id", new ObjectId(resourceId)),
            new Document("$set", permissions), new UpdateOptions().upsert(true));
}
 
Example #27
Source File: MongoDocumentHistory.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
public void add(HistoryEvent event) {
  Document insert =
      new Document(
          "$push",
          new Document("entities." + event.getRecordable().getInternalId(), convert(event)));

  collection.updateOne(
      new Document(DOC_ID, getDocumentId()), insert, new UpdateOptions().upsert(true));
}
 
Example #28
Source File: MongoDBSessionDataStorage.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public void save(SessionData sessionData) {
    String sessionId = sessionData.getId();
    this.sessions.updateOne(
            eq(SESSION_ID, sessionId),
            combine(
                    set(SESSION_ID, sessionId),
                    set(SESSION_TTL, new Date()),
                    set(SESSION_DATA, transcoder.encode(sessionData))),
            new UpdateOptions().upsert(true));
}
 
Example #29
Source File: MongoCollectionImpl.java    From mongo-java-driver-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<UpdateResult> updateMany(final Bson filter, final Bson update, final UpdateOptions options) {
    return RxObservables.create(Observables.observe(new Block<SingleResultCallback<UpdateResult>>() {
        @Override
        public void apply(final SingleResultCallback<UpdateResult> callback) {
            wrapped.updateMany(filter, update, options, callback);
        }
    }), observableAdapter);
}
 
Example #30
Source File: MongoCollectionImpl.java    From mongo-java-driver-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<UpdateResult> updateOne(final Bson filter, final Bson update, final UpdateOptions options) {
    return RxObservables.create(Observables.observe(new Block<SingleResultCallback<UpdateResult>>() {
        @Override
        public void apply(final SingleResultCallback<UpdateResult> callback) {
            wrapped.updateOne(filter, update, options, callback);
        }
    }), observableAdapter);
}