在java中使用MongoDB db.collection.remove(query)

时间:2013-11-21 23:42:50

标签: java mongodb mongodb-java

MongoDB Java驱动程序中是否有一种方法可以调用我在MongoDB shell文档中看到的db.collection.remove(query)方法? 也就是说,我知道我需要找到我想从MongoDB中删除的所有文档的确切标准,但我找不到一种方法来一次调用删除那些记录。我能弄清楚的就是找到文件然后逐一删除它们。

我明白这一点 http://docs.mongodb.org/manual/reference/method/db.collection.remove/ 这意味着应该有一种方法可以做到这一点,但我无法弄清楚Java调用是否让我接到那个电话。

感谢您的帮助

3 个答案:

答案 0 :(得分:8)

删除age属性为25的文档。

MongoClient mongo = new MongoClient(new ServerAddress("localhost", 27017));
DB db = mongo.getDB("thedb");
DBCollection collection = db.getCollection("test");

BasicDBObject query = new BasicDBObject();
query.append("age", 25);

collection.remove(query);

DBCollectionBasicDBObject是Java API中最重要的两个类。

答案 1 :(得分:1)

另外,要从您的文档中删除特定值,您可以在Mongo Java 3.2中使用以下代码

Document docToDelete = new Document("Designation", "SE-1");
objDbCollection.findOneAndUpdate(new Document("Company", "StackOverflow"), new Document("$unset", docToDelete));

上面的代码首先会找到具有company = StackOverflow的文档,然后从该文档中取消设置= SE-1键/值。

答案 2 :(得分:1)

添加和更新Mongo

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();
  }