How to Limit Delete to a MongoDB Collection using Java

Introduction

If you’re working with data in MongoDB, there will be times when you need to delete documents, but you want to limit that deletion to documents that meet specific criteria. Deleting documents is a permanent operation, so you need to make sure you know how to proceed. Fortunately, it’s easy to accomplish a limited deletion in Java with just a few lines of code. In this article, we’ll show you the simple two-step process for limiting the deletion of MongoDB documents in a MongoDB collection using Java.

Prerequisites

Before we start looking at our code examples, it’s important to review the prerequisites for the task and make sure all the system requirements are in place:

  • First, you must confirm that both MongoDB and the MongoDB Java driver have been installed and properly configured beforehand.

  • You must also verify that the latest Java JDK has been properly installed and configured beforehand.

  • Finally, you must confirm that the MongoDB service is up and running.

NOTE: Throughout this article, we’ll assume that the MongoDB version being used is 4.0 and the MongoDB Java Driver is 3.8.2.

The MongoDB Dataset

If you plan to follow along with the examples we present in this tutorial, it’s helpful to be working with the same data. The following dataset will be used in this tutorial. You can create your own test collection to use with the example code in this article:

IDNameRatingCountry
5ceb7d233fd48a1ebd04318eChang Kai-shek11China
5ceb7d233fd48a1ebd04318fSun Yat-sen8China
5ceb7d233fd48a1ebd043190Muammar al-Gaddafi15Libya
5ceb7d233fd48a1ebd043191Oda Nobunaga15Japan
5ceb7d233fd48a1ebd043192Cao Cao19China
5ceb7d233fd48a1ebd043193Sun Tzu10China

Get access to the MongoDB Deployment

Now that we’ve reviewed the system requirements and created a sample dataset, we can begin looking at some code. We’ll begin by instantiating a new MongoClient object. When we do this, we specify both the hostname and the port of our local deployment, as shown below:

MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");

Finding the Documents to Be Deleted

Next, we’ll review the two-step process for performing a limited deletion of documents from a MongoDB collection. The code shown below will find MongoDB documents that match the criteria and use the limit() method to limit the returned MongoDB documents:

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find(eq("country","China")).limit(2);

In this code segment, we first accessed the specified database "warlordDB". We then accessed the "warlordCollection" collection. In the same line, we used the find() method to retrieve documents where the value of "country" was "China". Note that we limited the number of results being returned to 2.

Deleting the Retrieved Documents from the MongoDB Collection.

In the next step, we’re going to go through the documents returned from the query and delete them. The code shown below will perform the deletion of the MongoDB documents retrieved from the previous section:

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
Document doc = cursor.next();
coll.deleteMany(doc);
}
} finally {
cursor.close();
}

In this segment of code, we begin by creating a cursor that will iterate over the results of our previous query. Notice that the deleteMany() method is called inside the while loop. What’s happening is that while the iterator loops through the cursor, the item that was found (doc) is being deleted at the same time.

Conclusion

When you delete documents from a MongoDB collection, you want to proceed with caution because deletion is a permanent operation. If you want to limit the deletion of documents to those that meet specific criteria, it’s easy to accomplish this task with just two easy steps: first, do a query for the documents that you’d like to delete, and then iterate through those results, deleting each individual document as you go. Using the step-by-step instructions and examples provided in this article, you’ll have no trouble limiting the deletion of MongoDB documents in a MongoDB collection using Java.

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.