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 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();
}
use of com.mongodb.reactivestreams.client.MongoCollection in project immutables by immutables.
the class MongoSession method query.
private Publisher<?> query(StandardOperations.Select select) {
final Query query = select.query();
final boolean hasProjections = query.hasProjections();
boolean useAggregationPipeline = query.hasAggregations() || query.distinct() || query.count() && query.limit().isPresent();
ExpressionNaming expressionNaming = useAggregationPipeline ? ExpressionNaming.from(UniqueCachedNaming.of(query.projections())) : expression -> pathNaming.name((Path) expression);
MongoCollection<?> collection = this.collection;
if (hasProjections) {
// add special TupleCodecProvider for projections
CodecRegistry newRegistry = CodecRegistries.fromRegistries(this.collection.getCodecRegistry(), CodecRegistries.fromProviders(new TupleCodecProvider(query, expressionNaming)));
collection = this.collection.withDocumentClass(ProjectedTuple.class).withCodecRegistry(newRegistry);
}
if (useAggregationPipeline) {
// aggregations
AggregationQuery agg = new AggregationQuery(query, pathNaming);
if (query.count()) {
// also for empty result-set mongo does not return single(0) but empty publisher
return Flowable.fromPublisher(collection.aggregate(agg.toPipeline(), BsonDocument.class)).map(d -> d.get("count").asNumber().longValue()).defaultIfEmpty(// return Single.just(0) for empty publisher
0L);
}
return collection.aggregate(agg.toPipeline(), ProjectedTuple.class);
}
Bson filter = toBsonFilter(query);
if (query.count()) {
// simple form of count all (without distinct, aggregations etc.) : count(*)
return Flowable.fromPublisher(collection.countDocuments(filter));
}
final FindPublisher<?> find = collection.find(filter);
if (!query.collations().isEmpty()) {
// add sorting
final Function<Collation, Bson> toSortFn = col -> {
final String path = col.path().toStringPath();
return col.direction().isAscending() ? Sorts.ascending(path) : Sorts.descending(path);
};
final List<Bson> sorts = query.collations().stream().map(toSortFn).collect(Collectors.toList());
find.sort(Sorts.orderBy(sorts));
}
query.limit().ifPresent(limit -> find.limit((int) limit));
query.offset().ifPresent(offset -> find.skip((int) offset));
if (hasProjections) {
List<String> fields = query.projections().stream().map(p -> pathNaming.name((Path) p)).collect(Collectors.toList());
find.projection(Projections.include(fields));
return find;
}
// post-process result with projections
return find;
}
use of com.mongodb.reactivestreams.client.MongoCollection in project mongo-java-driver by mongodb.
the class GridFSUploadPublisherImpl method createCheckAndCreateIndexesMono.
private Mono<Void> createCheckAndCreateIndexesMono() {
MongoCollection<Document> collection = filesCollection.withDocumentClass(Document.class).withReadPreference(primary());
FindPublisher<Document> findPublisher;
if (clientSession != null) {
findPublisher = collection.find(clientSession);
} else {
findPublisher = collection.find();
}
AtomicBoolean collectionExists = new AtomicBoolean(false);
return Mono.create(sink -> Mono.from(findPublisher.projection(PROJECTION).first()).subscribe(d -> collectionExists.set(true), sink::error, () -> {
if (collectionExists.get()) {
sink.success();
} else {
checkAndCreateIndex(filesCollection.withReadPreference(primary()), FILES_INDEX).doOnError(sink::error).doOnSuccess(i -> {
checkAndCreateIndex(chunksCollection.withReadPreference(primary()), CHUNKS_INDEX).doOnError(sink::error).doOnSuccess(sink::success).subscribe();
}).subscribe();
}
}));
}
use of com.mongodb.reactivestreams.client.MongoCollection in project mongo-java-driver by mongodb.
the class GridFSPublisherCreator method createDeletePublisher.
public static Publisher<Void> createDeletePublisher(final MongoCollection<GridFSFile> filesCollection, final MongoCollection<Document> chunksCollection, @Nullable final ClientSession clientSession, final BsonValue id) {
notNull("filesCollection", filesCollection);
notNull("chunksCollection", chunksCollection);
notNull("id", id);
BsonDocument filter = new BsonDocument("_id", id);
Publisher<DeleteResult> fileDeletePublisher;
if (clientSession == null) {
fileDeletePublisher = filesCollection.deleteOne(filter);
} else {
fileDeletePublisher = filesCollection.deleteOne(clientSession, filter);
}
return Mono.from(fileDeletePublisher).flatMap(deleteResult -> {
if (deleteResult.wasAcknowledged() && deleteResult.getDeletedCount() == 0) {
throw new MongoGridFSException(format("No file found with the ObjectId: %s", id));
}
if (clientSession == null) {
return Mono.from(chunksCollection.deleteMany(new BsonDocument("files_id", id)));
} else {
return Mono.from(chunksCollection.deleteMany(clientSession, new BsonDocument("files_id", id)));
}
}).flatMap(i -> Mono.empty());
}
Aggregations