【问题标题】:How to delete all documents in mongodb collection in java如何在java中删除mongodb集合中的所有文档
【发布时间】:2015-06-25 18:49:01
【问题描述】:

我想删除 java 集合中的所有文档。这是我的代码:

MongoClient client = new MongoClient("10.0.2.113" , 27017);
        MongoDatabase db = client.getDatabase("maindb");
        db.getCollection("mainCollection").deleteMany(new Document());

这是正确的做法吗?

我正在使用 MongoDB 3.0.2

【问题讨论】:

  • 您要删除特定的匹配文档还是删除整个集合?
  • 集合中的所有文档。

标签: java mongodb mongodb-java


【解决方案1】:

使用 API >= 3.0:

MongoClient mongoClient = new MongoClient("127.0.0.1" , 27017);
MongoDatabase db = mongoClient.getDatabase("maindb");
db.getCollection("mainCollection").deleteMany(new Document());

要删除集合(文档索引),您仍然可以使用:

db.getCollection("mainCollection").drop();

https://docs.mongodb.org/getting-started/java/remove/#remove-all-documents

【讨论】:

    【解决方案2】:

    要删除所有文档,请使用 BasicDBObject 或 DBCursor,如下所示:

    MongoClient client = new MongoClient("10.0.2.113" , 27017);
    MongoDatabase db = client.getDatabase("maindb");
    MongoCollection collection = db.getCollection("mainCollection")
    
    BasicDBObject document = new BasicDBObject();
    
    // Delete All documents from collection Using blank BasicDBObject
    collection.deleteMany(document);
    
    // Delete All documents from collection using DBCursor
    DBCursor cursor = collection.find();
    while (cursor.hasNext()) {
        collection.remove(cursor.next());
    }
    

    【讨论】:

    • 这两种方法有什么区别?
    【解决方案3】:

    如果要删除集合中的所有文档,请使用以下代码:

     db.getCollection("mainCollection").remove(new BasicDBObject());
    

    或者如果你想删除整个集合然后使用这个:

    db.getCollection("mainCollection").drop();
    

    【讨论】:

    • 如果您打算继续使用它,建议不要使用 drop() 截断集合。您可能会收到一个不稳定的错误“操作中止,因为:集合上的所有索引都已删除”。这显然是因为索引销毁是异步的。
    【解决方案4】:

    对于较新的 mongodb 驱动程序,您可以使用 FindIterable 删除集合中的所有文档。

    FindIterable<Document> findIterable = collection.find();
           for (Document document : findIterable) {
             collection.deleteMany(document);
           }
    

    【讨论】:

      猜你喜欢
      • 2017-02-21
      • 1970-01-01
      • 2021-02-19
      • 2021-02-01
      • 1970-01-01
      • 2020-09-08
      相关资源
      最近更新 更多