Java MongoDB Driver 3.3.0 - Delete Document(s)

 Posted On  | Yashwant Chavan 

In this article we will learn how to delete document using Java MongoDB Driver 3.3.0. MongoDB provides flexibility to delete one or more documents within the collection based on the filter condition. Learn more about deleteOne() and deleteMany() methods with example.

Tools and Technologies

Basically we are using below maven dependencies

  1. Maven 3.0.4
  2. JDK 1.8
  3. Mongo Java Driver 3.3.0

Maven Dependencies

To use the mongodb java driver, Define respected maven dependencies of mongo-java-driver in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicalkeeda</groupId>
    <artifactId>JavaExamples</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>
</project>

Connecting to database

A MongoDB client internally uses the connection pooling mechanism. It has one MongoClient instance for the entire JVM. To connect the local mongoDb database use host name (localhost) and default port number (27017).

MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

Get the database instance

Once you are successfully connected, access the mongoDB database e.g.(technicalkeeda).

 MongoDatabase database = mongoClient.getDatabase("technicalkeeda");

Get the Collection

Get the collection named as books from the database. It will create the collection if the collection does not exist.

 MongoCollection<Document> books = database.getCollection("books");

Delete One

Delete single document within the collection base on specified filter condition. e.g. deleteOne(Bson filter) Filter query is set as book_id = 1 eq("book_id", "1")

filter - a document describing the query filter, which may not be null.

The delete methods return a DeleteResult which provides information about how many documents are deleted.

 DeleteResult deleteResult = books.deleteOne(eq("book_id", "1"));
 System.out.println("deleteOne() - # of records deleted - " + deleteResult.getDeletedCount());

Delete Many

Delete multiple documents within the collection based on the filter query. Where filter condition is set as book_id >= 3. gte("book_id", "3")

 deleteResult = books.deleteMany(gte("book_id", "3"));
 System.out.println("deleteOne() - # of records deleted - " + deleteResult.getDeletedCount());

mongoDB Delete Document(s) Full Example

package com.technicalkeeda.app;

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

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;

public class App {
    public static void main(String[] args) {
        new App().delete();
    }

    public void delete() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
        MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
        List < Document > booksList = new ArrayList < Document > ();

        try {
            MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
            // using insertOne
            MongoCollection < Document > books = database.getCollection("books");

            booksList.add(
                new Document("authors", new Document().append("author_id", "1").append("name", "Chetan Bhagat"))
                .append("book_id", "1").append("title", "One Indian Girl").append("isbn", "8129142147")
                .append("price", "$14.99").append("publish_date", format.parse("2016-10-01T00:00:00Z")));

            booksList
                .add(new Document("authors", new Document().append("author_id", "2").append("name", "Sarina Singh"))
                    .append("book_id", "2").append("title", "Lonely Planet India").append("isbn", "1743216769")
                    .append("price", "$34.99").append("publish_date", format.parse("2015-10-01T00:00:00Z")));

            booksList.add(new Document("authors", new Document().append("author_id", "3").append("name", "John Keay"))
                .append("book_id", "3").append("title", "India: A History").append("isbn", "0802145582")
                .append("price", "$20.00").append("publish_date", format.parse("2011-04-01T00:00:00Z")));

            booksList.add(
                new Document("authors", new Document().append("author_id", "4").append("name", "Sri Vishwanath"))
                .append("book_id", "4")
                .append("title", "Eight Spiritual Laws Everyone Should Know By Heart")
                .append("isbn", "0802145582").append("price", "Rs 54")
                .append("publish_date", format.parse("2011-04-01T00:00:00Z")));

            books.insertMany(booksList);
            System.out.println("Display Collection After Insertion:- ");
            display(books);

            DeleteResult deleteResult = books.deleteOne(eq("book_id", "1"));
            System.out.println("deleteOne() - # of records deleted - " + deleteResult.getDeletedCount());

            deleteResult = books.deleteMany(gte("book_id", "3"));
            System.out.println("deleteOne() - # of records deleted - " + deleteResult.getDeletedCount());
            System.out.println("Display Collection After Deletion:- ");
            display(books);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mongoClient.close();
        }
    }

    public void display(MongoCollection < Document > books) {

        MongoCursor < Document > cursor = books.find().iterator();
        try {
            while (cursor.hasNext()) {
                Document book = cursor.next();
                System.out.println(book);
            }
        } finally {
            cursor.close();
        }

    }

}

Program Output

Display Collection After Insertion:- 
Document{{_id=57e8a5c54ee8370f9c90faf8, authors=Document{{author_id=1, name=Chetan Bhagat}}, book_id=1, title=One Indian Girl, isbn=8129142147, price=$14.99, publish_date=Sat Oct 01 00:00:00 IST 2016}}
Document{{_id=57e8a5c54ee8370f9c90faf9, authors=Document{{author_id=2, name=Sarina Singh}}, book_id=2, title=Lonely Planet India, isbn=1743216769, price=$34.99, publish_date=Thu Oct 01 00:00:00 IST 2015}}
Document{{_id=57e8a5c54ee8370f9c90fafa, authors=Document{{author_id=3, name=John Keay}}, book_id=3, title=India: A History, isbn=0802145582, price=$20.00, publish_date=Fri Apr 01 00:00:00 IST 2011}}
Document{{_id=57e8a5c54ee8370f9c90fafb, authors=Document{{author_id=4, name=Sri Vishwanath}}, book_id=4, title=Eight Spiritual Laws Everyone Should Know By Heart, isbn=0802145582, price=Rs 54, publish_date=Fri Apr 01 00:00:00 IST 2011}}
deleteOne() - # of records deleted - 1
deleteOne() - # of records deleted - 2
Display Collection After Deletion:- 
Document{{_id=57e8a5c54ee8370f9c90faf9, authors=Document{{author_id=2, name=Sarina Singh}}, book_id=2, title=Lonely Planet India, isbn=1743216769, price=$34.99, publish_date=Thu Oct 01 00:00:00 IST 2015}}

Shell Output

> use technicalkeeda
switched to db technicalkeeda
> show collections
books
system.indexes
> db.books.find().pretty()
{
        "_id" : ObjectId("57e8a3164ee83718ec4df44f"),
        "authors" : {
                "author_id" : "2",
                "name" : "Sarina Singh"
        },
        "book_id" : "2",
        "title" : "Lonely Planet India",
        "isbn" : "1743216769",
        "price" : "$34.99",
        "publish_date" : ISODate("2015-09-30T18:30:00Z")
}
>


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0640 seconds.