0

If a function call is done in java like:

collection.update(match, new BasicDBObject("$pull", update));

How can I know the number of documents updated in database after this statement execution?

And my other problem is, that I want to remove an element from an array in a document, if that element exists the collection. How can I do that easily? Should I query to find whether it is present in collection and then delete it or is there any other easier way?

4

1 回答 1

0

1) DBCollection.html#update方法返回一个WriteResult 对象,该对象包含一个n属性,该属性包含写入操作中受影响的文档数。

2)我认为没有办法在一次操作中做到这一点。如果在插入时刻该元素已经在其他文档的数组中,则可以进行更新以从数组中删除该元素。像这样的东西:

DBObject newElement = ...

DBObject query = BasicDBObjectBuilder.start()
    .add("array", newElement)
    .get();

DBObject update = BasicDBObjectBuilder.start()
    .push("$pull")
        .add("array", newElement)
    .pop()
    .get(); 

collection.update(query, update);
collection.insert(newElement);
于 2013-04-04T18:41:47.533 回答