Quick Start: Java and MongoDB - Delete Operations

Maxime Beugnet

#Java
Quick Start Java and MongoDB

In a previous blog post, I showed you how to update documents in MongoDB using Java. In this blog post, I will show you how to delete these documents.

Getting Set Up

Just like in the previous blog post, I will use the same repository. If you don't have a copy of it yet, you can clone it:

git clone https://github.com/mongodb-developer/java-quick-start

If you have previously cloned this repository, just make sure you are using the latest version:

git pull

If you didn't set up your free cluster on MongoDB Atlas, now is great time to do so. You have all the instructions in this blog post.

Created Data

In the previous blog post, we created the class Update. This time we will work in the Delete class.

In my create blog post, we wrote 11 new grades, one for the student with {"student_id": 10000.0} and 10 for the student with {"student_id": 10001.0} in the sample_training.grades collection. In my update blog post, we created one more document with an upsert operation for the student with {"student_id": 10002.0}.

We will delete theses documents in this blog post and I will also show you how to delete the entire grades collection.

As a reminder, here are the grades of my student with {"student_id": 10000.0} after being created in the Create class and updated in the Update class.

MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.grades.find({student_id:10000}).pretty()
{
	"_id" : ObjectId("5ddebfd746ea360fbe348e13"),
	"student_id" : 10000,
	"scores" : [
		{
			"type" : "exam",
			"score" : 123.13548598638322
		},
		{
			"type" : "quiz",
			"score" : 8.526314769698718
		},
		{
			"type" : "homework",
			"score" : 89.23738295333914
		},
		{
			"type" : "homework",
			"score" : 14.952033948082022
		}
	],
	"comment" : "You should learn MongoDB!",
	"comments" : [
		"This comment is uniq"
	],
	"new_class_id" : 1,
	"x" : 10
}

We also discussed BSON types in the create blog post and we noted that student_id and class_id are doubles.

MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison.

Do not be surprised in this blog post if I filter with an integer number and match a document which contains a double number for example. If you want to filter documents by value types, you can use the $type operator.

You can read more about type bracketing and comparison and sort order in our documentation.

Delete One Document

Let's delete the document above. To achieve this, we will use the method deleteOne.

Please create a class Delete in the com.mongodb.quickstart package with this code:

package com.mongodb.quickstart;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.logging.Level;
import java.util.logging.Logger;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.gte;

public class Delete {

    public static void main(String[] args) {
        Logger.getLogger("org.mongodb.driver").setLevel(Level.WARNING);

        try (MongoClient mongoClient = MongoClients.create(System.getProperty("mongodb.uri"))) {
            MongoDatabase sampleTrainingDB = mongoClient.getDatabase("sample_training");
            MongoCollection<Document> gradesCollection = sampleTrainingDB.getCollection("grades");

            // delete one document
            Bson filter = eq("student_id", 10000);
            DeleteResult result = gradesCollection.deleteOne(filter);
            System.out.println(result);
        }
    }
}

As you can see in this example, the method deleteOne only takes one parameter: a filter, just like the find() operation.

In order to run this program, make sure you set up your mongodb.uri in your system properties using your IDE if you want to run this code in your favorite IDE (see my first blog post for more details).

Alternatively, you can use this maven command line in your root project (where the src folder is):

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Delete" -Dmongodb.uri="mongodb+srv://USERNAME:PASSWORD@cluster0-abcde.mongodb.net/test?w=majority"

The standard output should look like this:

AcknowledgedDeleteResult{deletedCount=1}

FindOneAndDelete()

You are emotionally attached to your document and you want a chance to see it one last time before it's too late? We have what you need.

The method findOneAndDelete() allows you to retrieve a document and delete it in a single atomic operation.

Here is how it works:

Bson filter = eq("student_id", 10002);
Document doc = gradesCollection.findOneAndDelete(filter);
System.out.println(doc.toJson(JsonWriterSettings.builder().indent(true).build()));

Here is the output we get:

{
  "_id": {
    "$oid": "5ddec378224ad1d5cfac02b8"
  },
  "class_id": 10.0,
  "student_id": 10002.0,
  "comments": [
    "You will learn a lot if you read the MongoDB blog!"
  ]
}

Delete Many Documents

This time we will use deleteMany() instead of deleteOne() and we will use a different filter to match more documents.

Bson filter = gte("student_id", 10000);
DeleteResult result = gradesCollection.deleteMany(filter);
System.out.println(result);

As a reminder, you can learn more about all the query selectors in our documentation.

This is the output we get:

AcknowledgedDeleteResult{deletedCount=10}

Delete a Collection

Deleting all the documents from a collection will not delete the collection itself because a collection also contains metadata like the index definitions or the chunk distribution if your collection is sharded for example.

If you want to remove the entire collection and all the metadata associated with it, then you need to use the drop() method.

gradesCollection.drop();

The Final Code

package com.mongodb.quickstart;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.json.JsonWriterSettings;

import java.util.logging.Level;
import java.util.logging.Logger;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.gte;

public class Delete {

    public static void main(String[] args) {
        Logger.getLogger("org.mongodb.driver").setLevel(Level.WARNING);

        try (MongoClient mongoClient = MongoClients.create(System.getProperty("mongodb.uri"))) {
            MongoDatabase sampleTrainingDB = mongoClient.getDatabase("sample_training");
            MongoCollection<Document> gradesCollection = sampleTrainingDB.getCollection("grades");

            // delete one document
            Bson filter = eq("student_id", 10000);
            DeleteResult result = gradesCollection.deleteOne(filter);
            System.out.println(result);

            // findOneAndDelete operation
            filter = eq("student_id", 10002);
            Document doc = gradesCollection.findOneAndDelete(filter);
            System.out.println(doc.toJson(JsonWriterSettings.builder().indent(true).build()));

            // delete many documents
            filter = gte("student_id", 10000);
            result = gradesCollection.deleteMany(filter);
            System.out.println(result);

            // delete the entire collection and its metadata (indexes, chunk metadata, etc).
            gradesCollection.drop();
        }
    }
}

Wrapping Up

With this blog post we have now covered all the CRUD operations. You can find the links to the other blog posts of this series just below.

If you want to learn more and deepen your knowledge faster, I recommend you check out the M220J: MongoDB for Java Developers training available for free on MongoDB University.

In the next blog post, I will explain to you how to map MongoDB BSON documents to Java POJOs.

Articles in this Quick Start Java and MongoDB series: