2

Is there a way to delete all documents of a list(List) from a collection in bulk? I am thinking of something like: mongooperations.deleteAll(list);

It doesnt have to be a List tho, just any collection that i can collect the documents in and delete them in bulk, instead of deleting always single documents.

Daniel Jeney
  • 486
  • 1
  • 5
  • 19
  • How about this: https://stackoverflow.com/q/31058439/4636715 – vahdet Feb 10 '20 at 11:07
  • This just calls remove on each element as i see – Daniel Jeney Feb 10 '20 at 11:10
  • 1
    Instead of the `list` of documents you can input list of `_id`'s and use a query condition matching all the `_id`s (can use the `$in` operator). For example, `mongoTemplate.remove(Query query, String collectionName)` method, and the query specifies all the documents to be removed. – prasad_ Feb 10 '20 at 11:41
  • I think MongoRepository has a deleteAll method...https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/repository/support/SimpleMongoRepository.html#deleteAll-- – brijesh Feb 10 '20 at 11:44
  • @prasad_ yeh, that should work, thank you! not sure if i can mark a comment as an answer tho – Daniel Jeney Feb 10 '20 at 11:51
  • @btreport repository does have it, but mongo itself doesnt. For example when using MongoOperations – Daniel Jeney Feb 10 '20 at 11:52

1 Answers1

1

Here is the query to delete a list of document _ids. Assuming the _id's are numbers, this works:

List<Integer> ids = Arrays.asList(1, 2, 3, 4);
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testDB");
Query q = new Query(where("_id").in(ids));
List<Test> deletedDocs = mongoOps.findAllAndRemove(q, Test.class, "testColl");
// -or-
//List<Document> deletedDocs = mongoOps.findAllAndRemove(q, "testColl");
System.out.println(deletedDocs);
prasad_
  • 12,755
  • 2
  • 24
  • 36