简体   繁体   English

如何使用Java删除mongodb中的多个文档

[英]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. 我有一个Java程序,该程序根据特定的日期条件查找文档并删除所有文档。 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数据库时,它显示了2706文档。

MongoDB version: 3.0 MongoDB版本:3.0

Mongo-Java driver version: 3.1.0 Mongo-Java驱动程序版本:3.1.0

Mongo Shell command: Mongo Shell命令:

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程序,它或多或少地类似于上述命令。

Java code: Java代码:

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. 我不确定是否可以使用findOneAndDelete()方法。 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. 我在Google上搜索并找到了一些在线教程,但其中大多数都是基于旧版本2.1, 2.2等的。

Please guide. 请指导。

Found it. 找到了。

The deleteMany() method can be used for finding and deleting documents in a single shot. deleteMany()方法可用于单次查找和删除文档。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM