com.mongodb.client.model.Updates Java Examples

The following examples show how to use com.mongodb.client.model.Updates. 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: DBMember.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Mono<Void> delete() {
    LOGGER.debug("[DBMember {} / {}] Deletion", this.getId().asLong(), this.getGuildId().asLong());

    return Mono.from(DatabaseManager.getGuilds()
            .getCollection()
            .updateOne(Filters.eq("_id", this.getGuildId().asString()),
                    Updates.pull("members", Filters.eq("_id", this.getId().asString()))))
            .doOnNext(result -> LOGGER.trace("[DBMember {} / {}] Deletion result: {}",
                    this.getId().asLong(), this.getGuildId().asLong(), result))
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(GuildsCollection.NAME).inc())
            .then();
}
 
Example #3
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 #4
Source File: TopicModelTrainer.java    From baleen with Apache License 2.0 6 votes vote down vote up
private void writeTopicAssignmentsToMongo(
    InstanceList instances, TopicWords topicWords, ParallelTopicModel model) {
  IntStream.range(0, instances.size())
      .forEach(
          document -> {
            double[] topicDistribution = model.getTopicProbabilities(document);
            int maxAt = new MaximumIndex(topicDistribution).find();
            Instance instance = instances.get(document);

            List<String> iterator = topicWords.forTopic(maxAt);

            documentsCollection.findOneAndUpdate(
                Filters.eq(new ObjectId((String) instance.getName())),
                Updates.set(
                    TOPIC_FIELD,
                    new Document()
                        .append(KEYWORDS_FIELD, iterator.toString())
                        .append(TOPIC_NUMBER_FIELD, maxAt)));
          });
}
 
Example #5
Source File: DBGuild.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@code value} must be serializable or serialized.
 */
public <T> Mono<UpdateResult> updateSetting(Setting setting, T value) {
    LOGGER.debug("[DBGuild {}] Setting update: {}={}", this.getId().asLong(), setting, value);

    return Mono.from(DatabaseManager.getGuilds()
            .getCollection()
            .updateOne(
                    Filters.eq("_id", this.getId().asString()),
                    Updates.set(String.format("settings.%s", setting), value),
                    new UpdateOptions().upsert(true)))
            .doOnNext(result -> LOGGER.trace("[DBGuild {}] Setting update result: {}",
                    this.getId().asLong(), result))
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(GuildsCollection.NAME).inc());
}
 
Example #6
Source File: DBGuild.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public Mono<UpdateResult> removeSetting(Setting setting) {
    LOGGER.debug("[DBGuild {}] Setting deletion: {}", this.getId().asLong(), setting);

    return Mono.from(DatabaseManager.getGuilds()
            .getCollection()
            .updateOne(
                    Filters.eq("_id", this.getId().asString()),
                    Updates.unset(String.format("settings.%s", setting))))
            .doOnNext(result -> LOGGER.trace("[DBGuild {}] Setting deletion result: {}",
                    this.getId().asLong(), result))
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(GuildsCollection.NAME).inc());
}
 
Example #7
Source File: DBMember.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Void> insert() {
    LOGGER.debug("[DBMember {} / {}] Insertion", this.getId().asLong(), this.getGuildId().asLong());

    return Mono.from(DatabaseManager.getGuilds()
            .getCollection()
            .updateOne(Filters.eq("_id", this.getGuildId().asString()),
                    Updates.push("members", this.toDocument()),
                    new UpdateOptions().upsert(true)))
            .doOnNext(result -> LOGGER.trace("[DBMember {} / {}] Insertion result: {}",
                    this.getId().asLong(), this.getGuildId().asLong(), result))
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(GuildsCollection.NAME).inc())
            .then();
}
 
Example #8
Source File: Relic.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public Mono<UpdateResult> activate(Snowflake userId, @Nullable Snowflake guildId) {
    LOGGER.debug("[Relic {}] Activation", this.getId());

    return Mono.from(DatabaseManager.getPremium()
            .getCollection()
            .updateOne(Filters.eq("_id", this.getId()),
                    Updates.combine(
                            Updates.set("user_id", userId.asString()),
                            Updates.set("guild_id", guildId == null ? null : guildId.asString()),
                            Updates.set("activation", Instant.now().toEpochMilli()))))
            .doOnNext(result -> LOGGER.trace("[Relic {}] Activation result; {}", this.getId(), result));
}
 
Example #9
Source File: LotteryGambler.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Void> insert() {
    LOGGER.debug("[LotteryGambler {} / {}] Insertion", this.getUserId().asLong(), this.getGuildId().asLong());

    return Mono.from(DatabaseManager.getLottery()
            .getCollection()
            .updateOne(Filters.eq("_id", "gamblers"),
                    Updates.push("gamblers", this.toDocument()),
                    new UpdateOptions().upsert(true)))
            .doOnNext(result -> LOGGER.trace("[LotteryGambler {} / {}] Insertion result: {}",
                    this.getUserId().asLong(), this.getGuildId().asLong(), result))
            .then()
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(LotteryCollection.NAME).inc());
}
 
Example #10
Source File: LotteryCollection.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public Mono<UpdateResult> addToJackpot(long coins) {
    final long value = (long) Math.ceil(coins / 100.0f);

    LOGGER.debug("[Lottery] Jackpot update: {} coins", value);

    return Mono.from(this.getCollection()
            .updateOne(Filters.eq("_id", "jackpot"),
                    Updates.inc("jackpot", value),
                    new UpdateOptions().upsert(true)))
            .doOnNext(result -> LOGGER.trace("[Lottery] Jackpot update result: {}", result))
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(LotteryCollection.NAME).inc());
}
 
Example #11
Source File: AddAuthorsToBooks.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public static void main(String[] args) {
        MongoClient client = new MongoClient("localhost", 27017);
        MongoDatabase library = client.getDatabase("library");
        MongoCollection books = library.getCollection("books");
        
        try {
            Scanner scanner = new Scanner(AUTHORS_BOOKS);
            int n = 0;
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                Scanner lineScanner = new Scanner(line).useDelimiter("/");
                String author_id = lineScanner.next();
                String book_id = lineScanner.next();
                lineScanner.close();
                
//                Document doc = new Document().append("author_id", author_id);
                Document doc = new Document("author_id", author_id);
                books.updateOne(
                        eq("_id", book_id), 
                        Updates.addToSet("author", doc));
//                System.out.printf("%4d. %s, %s%n", ++n, _id, author);
            }
            scanner.close();
        } catch (IOException e) {
            System.err.println(e);
        }        
    }
 
Example #12
Source File: MongoIntegrationTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void update() {
    List<TestMongoEntity> entities = testEntities();
    collection.bulkInsert(entities);

    long updatedCount = collection.update(Filters.eq("string_field", entities.get(0).stringField), Updates.set("enum_field", TestMongoEntity.TestEnum.VALUE2));
    assertThat(updatedCount).isEqualTo(1);
    assertThat(collection.get(entities.get(0).id)).get().satisfies(loadedEntity -> assertThat(loadedEntity.enumField).isEqualTo(TestMongoEntity.TestEnum.VALUE2));
}
 
Example #13
Source File: MaxEntClassifierTrainer.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void writeClassificationToMongo(List<Classification> classify) {
  classify.forEach(
      classification -> {
        Instance instance = classification.getInstance();
        documentsCollection.findOneAndUpdate(
            Filters.eq(new ObjectId((String) instance.getName())),
            Updates.set(
                CLASSIFICATION_FIELD, classification.getLabeling().getBestLabel().toString()));
      });
}
 
Example #14
Source File: MongoNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private void moveNote(String noteId, String parentId, String noteName) {
  Document doc = new Document("$set",
      new Document(Fields.PID, parentId)
          .append(Fields.NAME, noteName));

  folders.updateOne(eq(Fields.ID, noteId), doc);
  notes.updateOne(eq(Fields.ID, noteId), Updates.set(Fields.NAME, noteName));
}
 
Example #15
Source File: TagRepository.java    From tutorials with MIT License 2 votes vote down vote up
/**
 * Adds a list of tags to the blog post with the given title.
 * 
 * @param title
 *            the title of the blog post
 * @param tags
 *            a list of tags to add
 * @return the outcome of the operation
 */
public boolean addTags(String title, List<String> tags) {
	UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
			Updates.addEachToSet(TAGS_FIELD, tags));
	return result.getModifiedCount() == 1;
}
 
Example #16
Source File: TagRepository.java    From tutorials with MIT License 2 votes vote down vote up
/**
 * Removes a list of tags to the blog post with the given title.
 * 
 * @param title
 *            the title of the blog post
 * @param tags
 *            a list of tags to remove
 * @return the outcome of the operation
 */
public boolean removeTags(String title, List<String> tags) {
	UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
			Updates.pullAll(TAGS_FIELD, tags));
	return result.getModifiedCount() == 1;
}