Java MongoDB : Delete document

In this tutorial, we show you how to use collection.remove() to delete documents from the collection.

1. Test Data

Insert 10 documents from number 1 to 10 for testing.

for (int i=1; i <= 10; i++) {
    collection.insert(new BasicDBObject().append("number", i));
}

2. DBCollection.remove()

See below code snippets to delete documents.

Example 1

Get first document and delete it. In this case, number = 1 is deleted.

    DBObject doc = collection.findOne(); //get first document
    collection.remove(doc);

Example 2

Puts query in a BasicDBObject. In this case, number = 2 is deleted.

    BasicDBObject document = new BasicDBObject();
    document.put("number", 2);
    collection.remove(document);

And Operator?

Two common mistakes :

  1. A query like this only delete number = 3.
    BasicDBObject document = new BasicDBObject();
    document.put("number", 2);
        document.put("number", 3); //override above value 2
    collection.remove(document);
  1. Nice try below, but query like this will not work, it will delete NOTHING.
    BasicDBObject document = new BasicDBObject();
    List<Integer> list = new ArrayList<Integer>();
    list.add(7);
    list.add(8);
    document.put("number", list);
    collection.remove(document);

For “AND” query, you need to use “$in” or “$and” operator, see example 5.

Example 3

Use BasicDBObject directly. In this case, number = 3 is deleted.

    collection.remove(new BasicDBObject().append("number", 3));

Example 4

Puts a $gt operator in a BasicDBObject object. In this case, number = 10 is deleted.

    BasicDBObject query = new BasicDBObject();
    query.put("number", new BasicDBObject("$gt", 9));
    collection.remove(query);

Example 5

Puts a $in operator in a BasicDBObject object, constructs the query in ArrayList. In this case, number = 4 and number = 5 are deleted.

    BasicDBObject query2 = new BasicDBObject();
    List<Integer> list = new ArrayList<Integer>();
    list.add(4);
    list.add(5);
    query2.put("number", new BasicDBObject("$in", list));
    collection.remove(query2);

Example 6

Use cursor to delete all available documents. (Not recommended, prefer example 7)

    DBCursor cursor = collection.find();
    while (cursor.hasNext()) {
        collection.remove(cursor.next());
    }

Example 7

Pass an empty BasicDBObject, and the entire documents will be deleted.

    collection.remove(new BasicDBObject());

Example 8

It deletes the entire documents and drop the collection.

    collection.drop();

Example 9

The remove() will returns a WrireResult object, it contains useful information about the remove operation. And you can uses getN() to get the number of documents affected.


       WriteResult result = collection.remove(query2);
       System.out.println("Number of documents are deleted : " + result.getN());

3. Full Example

Full example to show the different ways to delete documents.

package com.mkyong.core;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java MongoDB : Delete document
 * @author mkyong
 */

public class App {
    public static void main(String[] args) {

      try {

    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("yourdb");

    // get a single collection
    DBCollection collection = db.getCollection("dummyColl");

    //insert number 1 to 10 for testing
    for (int i=1; i <= 10; i++) {
        collection.insert(new BasicDBObject().append("number", i));
    }

    //remove number = 1
    DBObject doc = collection.findOne(); //get first document
    collection.remove(doc);

    //remove number = 2
    BasicDBObject document = new BasicDBObject();
    document.put("number", 2);
    collection.remove(document);

    //remove number = 3
    collection.remove(new BasicDBObject().append("number", 3));

    //remove number > 9 , means delete number = 10
    BasicDBObject query = new BasicDBObject();
    query.put("number", new BasicDBObject("$gt", 9));
    collection.remove(query);

    //remove number = 4 and 5
    BasicDBObject query2 = new BasicDBObject();
    List<Integer> list = new ArrayList<Integer>();
    list.add(4);
    list.add(5);
    query2.put("number", new BasicDBObject("$in", list));
    collection.remove(query2);

    //print out the document
    DBCursor cursor = collection.find();
        while(cursor.hasNext()) {
             System.out.println(cursor.next());
        }

        collection.drop();

        System.out.println("Done");

      } catch (UnknownHostException e) {
    e.printStackTrace();
      } catch (MongoException e) {
    e.printStackTrace();
      }

   }
}

Output…

{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee757"} , "number" : 6}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee758"} , "number" : 7}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee759"} , "number" : 8}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee75a"} , "number" : 9}

Done

發佈了1 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章