How to delete all documents in mongodb collection in java

前端 未结 4 903
半阙折子戏
半阙折子戏 2020-12-17 09:59

I want to delete all documents in a collection in java. Here is my code:

MongoClient client = new MongoClient(\"10.0.2.113\" , 27017);
        MongoDatabase         


        
4条回答
  •  攒了一身酷
    2020-12-17 10:39

    Using API >= 3.0:

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

    To drop the collection (documents and indexes) you still can use:

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

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

提交回复
热议问题