Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all documents in a collection with Springdata mongo Query

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.

like image 741
Kepler Avatar asked Feb 28 '18 11:02

Kepler


People also ask

How do I remove all files from a collection in MongoDB?

Here is the command to delete all the records of a collection in the MongoDB shell or MongoDB Compass shell (_MongoSH). show dbs -> to list all the database use test-database -> to select the database db. getCollection('orders'). deleteMany({}) -> to select the collection and deletes all the data.

What is the fastest operation to clear an entire collection in MongoDB?

MongoDB's db. collection. drop() is used to drop a collection from the database.

How do I delete all files in a collection in MongoDB Atlas?

You actually can't bulk delete in MongoDB Atlas. See MongoDB Atlas info on the filter section AKA Data Explorer. However you can run standard queries, like find, remove once you connect to the database using your Atlas credentials.

Which MongoDB command is used to remove document from a collection?

MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed.


Video Answer


2 Answers

You can use MongoTemplate directly

mongoTemplate.remove(new Query(), collectionName);
like image 166
Mohamd Ali Avatar answered Oct 04 '22 05:10

Mohamd Ali


You can drop the collection and create it again:

mongoTemplate.dropCollection("collectionName");
mongoTemplate.createCollection("collectionName");
like image 38
Riccardo Avatar answered Oct 04 '22 04:10

Riccardo