use of com.mongodb.reactivestreams.client.MongoCollection in project spring-data-mongodb by spring-projects.
the class ReactivePerformanceTests method writingObjectsUsingPlainDriver.
private long writingObjectsUsingPlainDriver(int numberOfPersons, WriteConcern concern) {
MongoCollection<Document> collection = mongo.getDatabase(DATABASE_NAME).getCollection("driver").withWriteConcern(concern);
List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(() -> persons.stream().map(it -> Mono.from(collection.insertOne(new Document(it.toDocument()))).block()));
return watch.getLastTaskTimeMillis();
}
use of com.mongodb.reactivestreams.client.MongoCollection in project immutables by immutables.
the class MongoSession method watch.
private <X> Publisher<WatchEvent<X>> watch(StandardOperations.Watch operation) {
final MongoCollection<X> collection = (MongoCollection<X>) this.collection;
if (operation.query().hasProjections()) {
return Flowable.error(new UnsupportedOperationException("Projections are not yet supported with watch operation"));
}
ChangeStreamPublisher<X> watch;
if (!operation.query().filter().isPresent()) {
// watch without filter
watch = collection.watch(collection.getDocumentClass());
} else {
// prefix all attributes with 'fullDocument.'
PathNaming naming = path -> "fullDocument." + this.pathNaming.name(path);
// reuse aggregation pipeline
AggregationQuery agg = new AggregationQuery(operation.query(), naming);
watch = collection.watch(agg.toPipeline(), collection.getDocumentClass());
}
return Flowable.fromPublisher(watch.fullDocument(FullDocument.UPDATE_LOOKUP)).map(MongoWatchEvent::fromChangeStream);
}
use of com.mongodb.reactivestreams.client.MongoCollection in project immutables by immutables.
the class MongoSession method update.
/**
* Uses <a href="https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/">replaceOne</a> operation
* with <a href="https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/">bulkWrite</a>. Right now has to convert
* object to BsonDocument to extract {@code _id} attribute.
*/
private <T> Publisher<WriteResult> update(StandardOperations.Update operation) {
ReplaceOptions options = new ReplaceOptions();
if (operation.upsert()) {
options.upsert(operation.upsert());
}
List<ReplaceOneModel<Object>> docs = operation.values().stream().map(value -> new ReplaceOneModel<>(new BsonDocument(Mongos.ID_FIELD_NAME, toBsonValue(keyExtractor.extract(value))), value, options)).collect(Collectors.toList());
Publisher<BulkWriteResult> publisher = ((MongoCollection<Object>) collection).bulkWrite(docs);
return Flowable.fromPublisher(publisher).map(x -> WriteResult.unknown());
}
use of com.mongodb.reactivestreams.client.MongoCollection in project immutables by immutables.
the class IdAttributeTest method idAttribute.
/**
* Test that {@code _id} attribute is persisted instead of {@code id}
*/
@Test
void idAttribute() {
StringHolderRepository repository = new StringHolderRepository(resource.backend());
ImmutableStringHolder holder = TypeHolder.StringHolder.generator().get().withId("id1");
repository.insertAll(Arrays.asList(holder, holder.withId("id2")));
MongoCollection<BsonDocument> collection = resource.collection(TypeHolder.StringHolder.class).withDocumentClass(BsonDocument.class);
List<BsonDocument> docs = Flowable.fromPublisher(collection.find()).toList().blockingGet();
Checkers.check(docs).hasSize(2);
// has _id attribute
Checkers.check(docs.stream().map(BsonDocument::keySet).flatMap(Collection::stream).collect(Collectors.toSet())).has("_id");
// does not have 'id' attribute only '_id' (with underscore which is mongo specific) in collected documents
Checkers.check(docs.stream().map(BsonDocument::keySet).flatMap(Collection::stream).collect(Collectors.toSet())).not().has("id");
Checkers.check(docs.stream().map(d -> d.get("_id").asString().getValue()).collect(Collectors.toList())).hasContentInAnyOrder("id1", "id2");
// using repository
Checkers.check(repository.findAll().fetch().stream().map(TypeHolder.StringHolder::id).collect(Collectors.toList())).hasContentInAnyOrder("id1", "id2");
}
use of com.mongodb.reactivestreams.client.MongoCollection in project spring-data-mongodb by spring-projects.
the class ReactiveMongoTemplate method doUpdate.
protected Mono<UpdateResult> doUpdate(final String collectionName, @Nullable Query query, @Nullable Update update, @Nullable Class<?> entityClass, final boolean upsert, final boolean multi) {
MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
Flux<UpdateResult> result = execute(collectionName, collection -> {
increaseVersionForUpdateIfNecessary(entity, update);
Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
}
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);
query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation);
if (!UpdateMapper.isUpdateObject(updateObj)) {
return collectionToUse.replaceOne(queryObj, updateObj, updateOptions);
}
if (multi) {
return collectionToUse.updateMany(queryObj, updateObj, updateOptions);
}
return collectionToUse.updateOne(queryObj, updateObj, updateOptions);
}).doOnNext(updateResult -> {
if (entity != null && entity.hasVersionProperty() && !multi) {
if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (dbObjectContainsVersionProperty(queryObj, entity))
throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: " + updateObj.toString() + " to collection " + collectionName);
}
}
});
return result.next();
}
Aggregations