Delete all documents in a collection with Springdata mongo Query

Kepler picture Kepler · Feb 28, 2018 · Viewed 10.9k times · Source

I want to implement a delete method which deletes all the documents in a collection. I am using mongo db with Spring Data.This could be done using db.myCollection.remove({}) in Mongo shell. But I want to write a method in my data access layer to do this.I am not using MongodbTemplate in my Dao class. I want to know how can I do this with Query.

Query query = new Query();

Could anybody please tell me how can I do it.

Answer

s7vr picture s7vr · Feb 28, 2018

Use MongoRepository's deleteAll(). Utilizes mongoTemplate behind the scene to call the remove method.

From calling method someRepository.deleteAll()

Drop collection may be efficient as other answer has noted. For that you will need to use MongoTemplate directly and call dropCollection with entity class or collection name.