Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all documents in mongodb collection in java

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 db = client.getDatabase("maindb");
        db.getCollection("mainCollection").deleteMany(new Document());

Is this the correct way to do this?

I am using MongoDB 3.0.2

like image 999
Viratan Avatar asked Jun 25 '15 18:06

Viratan


People also ask

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

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.

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

MongoDB's remove() method is used to remove a document from the collection.

How do I delete all records 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.


3 Answers

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

like image 145
hawkpatrick Avatar answered Oct 09 '22 03:10

hawkpatrick


To remove all documents use the BasicDBObject or DBCursor as follows:

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());
}
like image 33
chridam Avatar answered Oct 09 '22 03:10

chridam


If you want to remove all documents in collection then used below code :

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

Or If you want to drop whole collection then used this :

db.getCollection("mainCollection").drop();
like image 33
Yogesh Avatar answered Oct 09 '22 04:10

Yogesh