@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; } });
/** * Perform upsert: update single element or inserts a new one if none of the document matches. * <p> * <em>Note: Upsert operation requires special care to set or init all required attributes in case of insertion * (including but not limited to '_id'), so that valid document could be inserted into collection. * </em> * @return future of number of processed document (expected to be 1) */ public FluentFuture<Integer> upsert() { UpdateOptions options = new UpdateOptions(); options.upsert(true); return repository.doUpdate(criteria, collectRequiredUpdate(), options); }
/** * Update a single or all documents in the collection according to the specified arguments. * When upsert set to true, the new document will be inserted if there are no matches to the query filter. * * @param filter Bson filter * @param document Bson document * @param upsert a new document should be inserted if there are no matches to the query filter * @param many whether find all documents according to the query filter */ public void update(Bson filter, Bson document, boolean upsert, boolean many) { //TODO batch updating UpdateOptions options = new UpdateOptions(); if (upsert) { options.upsert(true); } if (many) { collection.updateMany(filter, document, options); } else { collection.updateOne(filter, document, options); } }
/** * Performs update and upsert bulk operations. * * @param query the {@link Query} to determine documents to update. * @param update the {@link Update} to perform, must not be {@literal null}. * @param upsert whether to upsert. * @param multi whether to issue a multi-update. * @return the {@link BulkOperations} with the update registered. */ private BulkOperations update(Query query, Update update, boolean upsert, boolean multi) { Assert.notNull(query, "Query must not be null!"); Assert.notNull(update, "Update must not be null!"); UpdateOptions options = new UpdateOptions(); options.upsert(upsert); query.getCollation().map(Collation::toMongoCollation).ifPresent(options::collation); if (multi) { models.add(new UpdateManyModel<>(query.getQueryObject(), update.getUpdateObject(), options)); } else { models.add(new UpdateOneModel<>(query.getQueryObject(), update.getUpdateObject(), options)); } return this; }
/** * Gets the options to apply. * * @return the update options * @deprecated use {@link #getReplaceOptions()} instead */ @Deprecated public UpdateOptions getOptions() { return new UpdateOptions() .bypassDocumentValidation(options.getBypassDocumentValidation()) .collation(options.getCollation()) .upsert(options.isUpsert()); }
@Override public void save(final Session session) { syncTtl(); String id = session.id(); Bson filter = Filters.eq("_id", id); Document doc = new Document() .append("_id", id) .append("_accessedAt", new Date(session.accessedAt())) .append("_createdAt", new Date(session.createdAt())) .append("_savedAt", new Date(session.savedAt())); // dump attributes Map<String, String> attributes = session.attributes(); attributes.forEach((k, v) -> doc.append(encode(k), v)); sessions.updateOne(filter, new Document("$set", doc), new UpdateOptions().upsert(true)); }
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse); UpdateOptions updateOptions = new UpdateOptions().upsert(upsert); query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation);
opts.upsert(upsert);
Bson setOnInsert = Document.parse("{'$setOnInsert': {'onlySetIfInsertDataInt': 789}}"); UpdateOptions updateOptions = new UpdateOptions(); updateOptions.upsert(true); Consumer<MongoClient> upsert = client -> client.getDatabase(DB_NAME).getCollection(this.getCollectionName()) .updateOne(Document.parse("{'_id' : 2}"), setOnInsert, updateOptions);
/** * Performs update and upsert bulk operations. * * @param query the {@link Query} to determine documents to update. * @param update the {@link Update} to perform, must not be {@literal null}. * @param upsert whether to upsert. * @param multi whether to issue a multi-update. * @return the {@link BulkOperations} with the update registered. */ private BulkOperations update(Query query, Update update, boolean upsert, boolean multi) { Assert.notNull(query, "Query must not be null!"); Assert.notNull(update, "Update must not be null!"); UpdateOptions options = new UpdateOptions(); options.upsert(upsert); query.getCollation().map(Collation::toMongoCollation).ifPresent(options::collation); if (multi) { models.add(new UpdateManyModel<>(query.getQueryObject(), update.getUpdateObject(), options)); } else { models.add(new UpdateOneModel<>(query.getQueryObject(), update.getUpdateObject(), options)); } return this; }
@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)); }
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse); UpdateOptions updateOptions = new UpdateOptions().upsert(upsert); query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation);
@Override public void setFunds(String bankAccount, int amount) { Document search = new Document("_id", bankAccount); Document update = new Document("_id", bankAccount).append("funds", amount); accountsCollection.updateOne(search, new Document("$set", update), new UpdateOptions().upsert(true)); }
public void save(@Nonnull ProjectDetails projectRecord) { Document document = objectMapper.convertValue(projectRecord, Document.class); collection.replaceOne(withProjectId(projectRecord.getProjectId()), document, new UpdateOptions().upsert(true)); cache.invalidate(projectRecord.getProjectId()); displayLanguagesCache.invalidate(projectRecord.getProjectId()); }
@Test public void testUpdateSetOnInsert() throws Exception { Document object = json("_id: 1"); collection.updateOne(object, json("$set: {b: 3}, $setOnInsert: {a: 3}"), new UpdateOptions().upsert(true)); assertThat(collection.find().first()).isEqualTo(json("_id: 1, b: 3, a: 3")); collection.updateOne(object, json("$set: {b: 4}, $setOnInsert: {a: 5}"), new UpdateOptions().upsert(true)); assertThat(collection.find().first()).isEqualTo(json("_id: 1, b: 4, a: 3")); // 'a' is unchanged }
@Test public void testUpsertOnIdWithPush() { Document update1 = json("$push: {c: {a: 1, b: 2}}"); Document update2 = json("$push: {c: {a: 3, b: 4}}"); collection.updateOne(json("_id: 1"), update1, new UpdateOptions().upsert(true)); collection.updateOne(json("_id: 1"), update2, new UpdateOptions().upsert(true)); Document expected = json("_id: 1, c: [{a: 1, b: 2}, {a: 3, b: 4}]"); assertThat(collection.find(json("'c.a':3, 'c.b':4")).first()).isEqualTo(expected); }
public V createOrUpdate(final V value, final long maxTime, final TimeUnit timeUnit) { final Document doc = encode(value); collectionWithWriteTimeout(maxTime, timeUnit) .replaceOne(byId(keyOf(value)), doc, new UpdateOptions().upsert(true)); return decode(doc); }
@Test public void testUpsertWithEmbeddedQuery() { collection.updateOne(json("_id: 1, 'e.i': 1"), json("$set: {a: 1}"), new UpdateOptions().upsert(true)); assertThat(collection.find(json("_id: 1")).first()).isEqualTo(json("_id: 1, e: {i: 1}, a: 1")); }