Refine search
/** * 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); } }
/** * 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()); }
UpdateOptions opts = new UpdateOptions(); opts.upsert(upsert); WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction); collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection; replaceOptions.collation(opts.getCollation()); replaceOptions.upsert(opts.isUpsert()); return collection.replaceOne(queryObj, updateObj, replaceOptions); } else { if (multi) { return collection.updateMany(queryObj, updateObj, opts); } else { return collection.updateOne(queryObj, updateObj, opts);
@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; } });
@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)); }
final MongoCollection<Document> collection = getCollection(context, flowFile).withWriteConcern(writeConcern); collection.insertOne((Document)doc); logger.info("inserted {} into MongoDB", new Object[] { flowFile }); } else { collection.replaceOne(query, (Document)doc, new UpdateOptions().upsert(upsert)); } else { BasicDBObject update = (BasicDBObject)doc; update.remove(updateKey); collection.updateOne(query, update, new UpdateOptions().upsert(upsert));
/** * 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); }
@Override public void processed(ICrawlData crawlData) { Document document = serializer.toDocument(Stage.PROCESSED, crawlData); // If the document does not exist yet, it will be inserted. If exists, // it will be updated. Bson filter = referenceFilter(crawlData.getReference()); collRefs.updateOne(filter, new Document("$set", document), new UpdateOptions().upsert(true)); // Remove from cache collCached.deleteOne(filter); }
/** * Update all documents in the collection according to the specified query filter. * When upsert set to true, the new document will be inserted if there are no matches to the query filter. * * @param filter * @param update * @param upsert */ public void update(Bson filter, Bson update, boolean upsert) { UpdateOptions options = new UpdateOptions(); if (upsert) { options.upsert(true); } collection.updateMany(filter, update, options); }
public void registerNode(LocalNodeConfig localNodeConfig, String serverAddress) throws Exception { MongoDatabase db = mongo.getDatabase(database); MongoCollection<Document> membershipCollection = db.getCollection(CLUSTER_MEMBERSHIP); Document index = new Document(); index.put(SERVER_ADDRESS, 1); index.put(INSTANCE, 1); System.out.println(localNodeConfig.getHazelcastPort()); IndexOptions options = new IndexOptions().unique(true); membershipCollection.createIndex(index, options); Document search = new Document(); search.put(SERVER_ADDRESS, serverAddress); search.put(INSTANCE, localNodeConfig.getHazelcastPort()); Document object = new Document(); object.put(SERVER_ADDRESS, serverAddress); object.put(INSTANCE, localNodeConfig.getHazelcastPort()); object.put(DATA, localNodeConfig.toDocument()); membershipCollection.replaceOne(search, object, new UpdateOptions().upsert(true)); }
@Override public boolean metaClassFor(Id id, ClassBean metaClass) { checkNotNull(id, "id"); checkNotNull(metaClass, "metaClass"); final String ownerId = idConverter.convert(id); final ClassDocument newMetaClass = ClassDocument.fromBean(metaClass); final Bson filter = eq(ModelDocument.F_ID, ownerId); final Bson existsFilter = and(filter, exists(ModelDocument.F_METACLASS)); final boolean notExists = documents.countDocuments(existsFilter, new CountOptions().limit(1)) == 0; if (notExists) { final Bson update = combine( setOnInsert(concat(ModelDocument.F_METACLASS, ClassDocument.F_NAME), newMetaClass.getName()), setOnInsert(concat(ModelDocument.F_METACLASS, ClassDocument.F_URI), newMetaClass.getUri()) ); documents.updateOne(filter, update, new UpdateOptions().upsert(true)); } return notExists; }
@Override public void saveStates(List<State> list) { MongoDbOperations.doDbOperation(() -> { List<WriteModel<Document>> operations = new ArrayList<>(); for (State state : list) { operations.add(new UpdateOneModel<>(new Document("clz", state.getSagaStateId()).append("sid", state.getId()), new Document("$set",new Document("s", state.getState())),new UpdateOptions().upsert(true))); } final BulkWriteResult bulkWriteResult = states.bulkWrite(operations); return bulkWriteResult; }); } }
/** * Construct a new instance. * * @param filter a document describing the query filter, which may not be null. * @param update a document describing the update, which may not be null. The update to apply must include only update operators. */ public UpdateOneModel(final Bson filter, final Bson update) { this(filter, update, new UpdateOptions()); }
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse); UpdateOptions updateOptions = new UpdateOptions().upsert(upsert); query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation); replaceOptions.upsert(updateOptions.isUpsert()); replaceOptions.collation(updateOptions.getCollation());
UpdateOptions updateOptions = new UpdateOptions(); updateOptions.upsert(true); //if true, will create a new doc in case of unmatched find updateOptions.bypassDocumentValidation(true); //set true/false
/** * Creates replace options from updateOptions. * * @param updateOptions the updateOptions * @return replace options */ public static ReplaceOptions createReplaceOptions(final UpdateOptions updateOptions) { notNull("updateOptions", updateOptions); List<? extends Bson> arrayFilters = updateOptions.getArrayFilters(); isTrue("ArrayFilters should be empty.", arrayFilters == null || arrayFilters.isEmpty()); return new ReplaceOptions() .bypassDocumentValidation(updateOptions.getBypassDocumentValidation()) .collation(updateOptions.getCollation()) .upsert(updateOptions.isUpsert()); }
() -> { ReplaceOneModel<BsonDocument> rom = (ReplaceOneModel<BsonDocument>)wm; assertTrue(rom.getOptions().isUpsert(), "replacement expected to be done in upsert mode"); BsonDocument filter = rom.getFilter().toBsonDocument(BsonDocument.class,null); assertEquals(1,filter.size(),"filter document should only contain "+DBCollection.ID_FIELD_NAME);
WriteRequest.Type.UPDATE) .multi(false) .upsert(updateOneModel.getOptions().isUpsert()) .collation(updateOneModel.getOptions().getCollation()) .arrayFilters(toBsonDocumentList(updateOneModel.getOptions().getArrayFilters())); } else if (writeModel instanceof UpdateManyModel) { UpdateManyModel<TDocument> updateManyModel = (UpdateManyModel<TDocument>) writeModel; WriteRequest.Type.UPDATE) .multi(true) .upsert(updateManyModel.getOptions().isUpsert()) .collation(updateManyModel.getOptions().getCollation()) .arrayFilters(toBsonDocumentList(updateManyModel.getOptions().getArrayFilters())); } else if (writeModel instanceof DeleteOneModel) { DeleteOneModel<TDocument> deleteOneModel = (DeleteOneModel<TDocument>) writeModel;
public void shouldTransformOperationSetOnInsert() throws InterruptedException { 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); .updateOne(Document.parse("{'_id' : 2}"), setOnInsertAndSet, updateOptions); primary().execute("update", upsertAndUpdate);
public UpdateResult replace(Bson query, Bson updates, boolean upsert) { UpdateOptions updateOptions = new UpdateOptions().upsert(upsert); return dbCollection.replaceOne(query, (Document) updates, updateOptions); }