How Java deletes documents from MongoDB collections
To delete documents from the MongoDB collection, you can use the 'deleteOne()' or 'deleteMany()' methods provided by the Java driver.
The following is a complete Java sample code:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
public class MongoDBDeleteExample {
public static void main(String[] args) {
//Connect to MongoDB database
MongoClient mongoClient = new MongoClient("localhost", 27017);
//Select Database
MongoDatabase database = mongoClient.getDatabase("testdb");
//Select Collection
MongoCollection<Document> collection = database.getCollection("testcollection");
//Delete a single document
collection.deleteOne(Filters.eq("name", "John Doe"));
//Delete multiple documents
collection.deleteMany(Filters.lt("age", 30));
}
}
This example code uses the Java driver's' deleteOne() 'and' deleteMany() 'methods to delete one document and multiple documents, respectively` The static method of the Filters' class is used to construct deletion conditions.
Assuming there are the following documents in the MongoDB collection 'testcollection':
json
{ "_id" : ObjectId("60a0f1434797c646c89b12e3"), "name" : "John Doe", "age" : 25 }
{ "_id" : ObjectId("60a0f14c4797c646c89b12e4"), "name" : "Jane Smith", "age" : 30 }
{ "_id" : ObjectId("60a0f1564797c646c89b12e5"), "name" : "Bob Johnson", "age" : 40 }
After running the above Java code, the documents in the MongoDB collection will be deleted. In this example, the document with 'name' as' John Doe 'was deleted, and the document with' age 'less than 30 was deleted.