Nital
Nital

Reputation: 6084

How to delete multiple documents in mongodb using java

I have a java program that finds documents based on certain date condition and removes all of them. I am not sure how to remove those documents once found. When I query the MongoDB database using following command it shows me 2706 documents present.

MongoDB version: 3.0

Mongo-Java driver version: 3.1.0

Mongo Shell command:

db.jobs.find({"startTime" : { $gte : "2015-11-04 00:00:00"}}).count();
Output: 2706

I have the following java program that does more or less similar to the above command.

Java code:

MongoDatabase database = DataSourceFactory.getDatabase(DatabaseType.MONGODB.name());
MongoCollection<Document> collection = database.getCollection("jobs");
//find and delete existing documents first
String currentDate = GenericUtils.getCurrentDate() + " 00:00:00";
Document doc = collection.findOneAndDelete(gte("startTime", currentDate));

I am not sure if usage of findOneAndDelete() method is the way to go. Do I have to write a loop that does this? Is there a way to find and remove all the records in a single shot?

Not sure how to remove all the records and get a count of how many got deleted.

I googled and found some online tutorials but most of them are based on older versions 2.1, 2.2 etc.

Please guide.

Upvotes: 2

Views: 4651

Answers (1)

Nital
Nital

Reputation: 6084

Found it.

The deleteMany() method can be used for finding and deleting documents in a single shot.

DeleteResult deleteResult = collection.deleteMany(gte("startTime", currentDate));
LOG.debug(deleteResult.getDeletedCount() + " document(s) deleted.....");

Upvotes: 1

Related Questions