use of com.mongodb.client.result.DeleteResult in project mongo-java-driver by mongodb.
the class QuickTour method main.
/**
* Run this main method to see the output of this quick example.
*
* @param args takes an optional single argument for the connection string
*/
public static void main(final String[] args) {
MongoClient mongoClient;
if (args.length == 0) {
// connect to the local database server
mongoClient = MongoClients.create();
} else {
mongoClient = MongoClients.create(args[0]);
}
// get handle to "mydb" database
MongoDatabase database = mongoClient.getDatabase("mydb");
// get a handle to the "test" collection
final MongoCollection<Document> collection = database.getCollection("test");
// drop all the data in it
ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
collection.drop().subscribe(successSubscriber);
successSubscriber.await();
// make a document and insert it
Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102));
ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
collection.insertOne(doc).subscribe(insertOneSubscriber);
insertOneSubscriber.await();
// get it (since it's the only one in there since we dropped the rest earlier on)
ObservableSubscriber<Document> documentSubscriber = new PrintDocumentSubscriber();
collection.find().first().subscribe(documentSubscriber);
documentSubscriber.await();
// now, lets add lots of little documents to the collection so we can explore queries and cursors
List<Document> documents = new ArrayList<>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
collection.insertMany(documents).subscribe(insertManySubscriber);
insertManySubscriber.await();
// find first
documentSubscriber = new PrintDocumentSubscriber();
collection.find().first().subscribe(documentSubscriber);
documentSubscriber.await();
// lets get all the documents in the collection and print them out
documentSubscriber = new PrintDocumentSubscriber();
collection.find().subscribe(documentSubscriber);
documentSubscriber.await();
// Query Filters
// now use a query to get 1 document out
documentSubscriber = new PrintDocumentSubscriber();
collection.find(eq("i", 71)).first().subscribe(documentSubscriber);
documentSubscriber.await();
// now use a range query to get a larger subset
documentSubscriber = new PrintDocumentSubscriber();
collection.find(gt("i", 50)).subscribe(documentSubscriber);
successSubscriber.await();
// range query with multiple constraints
documentSubscriber = new PrintDocumentSubscriber();
collection.find(and(gt("i", 50), lte("i", 100))).subscribe(documentSubscriber);
successSubscriber.await();
// Sorting
documentSubscriber = new PrintDocumentSubscriber();
collection.find(exists("i")).sort(descending("i")).first().subscribe(documentSubscriber);
documentSubscriber.await();
// Projection
documentSubscriber = new PrintDocumentSubscriber();
collection.find().projection(excludeId()).first().subscribe(documentSubscriber);
documentSubscriber.await();
// Aggregation
documentSubscriber = new PrintDocumentSubscriber();
collection.aggregate(asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))).subscribe(documentSubscriber);
documentSubscriber.await();
documentSubscriber = new PrintDocumentSubscriber();
collection.aggregate(singletonList(group(null, sum("total", "$i")))).first().subscribe(documentSubscriber);
documentSubscriber.await();
// Update One
ObservableSubscriber<UpdateResult> updateSubscriber = new OperationSubscriber<>();
collection.updateOne(eq("i", 10), set("i", 110)).subscribe(updateSubscriber);
updateSubscriber.await();
// Update Many
updateSubscriber = new OperationSubscriber<>();
collection.updateMany(lt("i", 100), inc("i", 100)).subscribe(updateSubscriber);
updateSubscriber.await();
// Delete One
ObservableSubscriber<DeleteResult> deleteSubscriber = new OperationSubscriber<>();
collection.deleteOne(eq("i", 110)).subscribe(deleteSubscriber);
deleteSubscriber.await();
// Delete Many
deleteSubscriber = new OperationSubscriber<>();
collection.deleteMany(gte("i", 100)).subscribe(deleteSubscriber);
deleteSubscriber.await();
// Create Index
OperationSubscriber<String> createIndexSubscriber = new PrintSubscriber<>("Create Index Result: %s");
collection.createIndex(new Document("i", 1)).subscribe(createIndexSubscriber);
createIndexSubscriber.await();
// Clean up
successSubscriber = new OperationSubscriber<>();
collection.drop().subscribe(successSubscriber);
successSubscriber.await();
// release resources
mongoClient.close();
}
use of com.mongodb.client.result.DeleteResult 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());
}
use of com.mongodb.client.result.DeleteResult in project spring-data-mongodb by spring-projects.
the class ExecutableRemoveOperationSupportTests method removeAllMatching.
// DATAMONGO-1563
@Test
void removeAllMatching() {
DeleteResult result = template.remove(Person.class).matching(query(where("firstname").is("han"))).all();
assertThat(result.getDeletedCount()).isEqualTo(1L);
}
use of com.mongodb.client.result.DeleteResult in project spring-data-mongodb by spring-projects.
the class ReactiveMongoTemplate method doRemove.
protected <T> Mono<DeleteResult> doRemove(String collectionName, Query query, @Nullable Class<T> entityClass) {
if (query == null) {
throw new InvalidDataAccessApiUsageException("Query passed in to remove can't be null!");
}
Assert.hasText(collectionName, "Collection name must not be null or empty!");
MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
DeleteContext deleteContext = queryOperations.deleteQueryContext(query);
Document queryObject = deleteContext.getMappedQuery(entity);
DeleteOptions deleteOptions = deleteContext.getDeleteOptions(entityClass);
Document removeQuery = deleteContext.getMappedQuery(entity);
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.REMOVE, collectionName, entityClass, null, removeQuery);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
return execute(collectionName, collection -> {
maybeEmitEvent(new BeforeDeleteEvent<>(removeQuery, entityClass, collectionName));
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Remove using query: %s in collection: %s.", serializeToJsonSafely(removeQuery), collectionName));
}
if (query.getLimit() > 0 || query.getSkip() > 0) {
FindPublisher<Document> cursor = new QueryFindPublisherPreparer(query, entityClass).prepare(//
collection.find(removeQuery)).projection(MappedDocument.getIdOnlyProjection());
return //
Flux.from(cursor).map(//
MappedDocument::of).map(//
MappedDocument::getId).collectList().flatMapMany(val -> {
return collectionToUse.deleteMany(MappedDocument.getIdIn(val), deleteOptions);
});
} else {
return collectionToUse.deleteMany(removeQuery, deleteOptions);
}
}).doOnNext(//
it -> maybeEmitEvent(new AfterDeleteEvent<>(queryObject, entityClass, collectionName))).next();
}
use of com.mongodb.client.result.DeleteResult in project spring-data-mongodb by spring-projects.
the class MongoTemplateTests method removeShouldConsiderSkipAndSort.
// DATAMONGO-1870
@Test
public void removeShouldConsiderSkipAndSort() {
List<Sample> samples = //
IntStream.range(0, 100).mapToObj(//
i -> new Sample("id-" + i, i % 2 == 0 ? "stark" : "lannister")).collect(Collectors.toList());
template.insertAll(samples);
DeleteResult wr = template.remove(new Query().skip(25).with(Sort.by("field")), Sample.class);
assertThat(wr.getDeletedCount()).isEqualTo(75L);
assertThat(template.count(new Query(), Sample.class)).isEqualTo(25L);
assertThat(template.count(query(where("field").is("lannister")), Sample.class)).isEqualTo(25L);
assertThat(template.count(query(where("field").is("stark")), Sample.class)).isEqualTo(0L);
}
Aggregations