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.

6
  • How about this: stackoverflow.com/q/31058439/4636715 Commented Feb 10, 2020 at 11:07
  • This just calls remove on each element as i see Commented Feb 10, 2020 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 _ids (can use the $in operator). For example, mongoTemplate.remove(Query query, String collectionName) method, and the query specifies all the documents to be removed. Commented Feb 10, 2020 at 11:41
  • I think MongoRepository has a deleteAll method...docs.spring.io/spring-data/mongodb/docs/current/api/org/… Commented Feb 10, 2020 at 11:44
  • @prasad_ yeh, that should work, thank you! not sure if i can mark a comment as an answer tho Commented Feb 10, 2020 at 11:51

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.