下面列出了怎么用com.mongodb.client.model.Updates的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
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());
}
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)));
});
}
/**
* {@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());
}
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());
}
@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();
}
@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();
}
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));
}
@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());
}
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());
}
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);
}
}
@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));
}
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()));
});
}
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));
}
/**
* 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;
}
/**
* 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;
}