我有像这样的JSON:
{
"_id" : "1",
"_class" : "com.model.Test",
"itemList" : [
{
"itemID" : "1",
"itemName" : "Foo",
"resources" : [
{
"resourceID" : "1",
"resourceName" : "Foo Test1"
}, {
"resourceID" : "2",
"resourceName" : "Foo Test2"
}
]
}
]
}我需要能够删除itemList的一条记录。我做了以下工作:
public void removeItemByID(String docID, String itemID) throws Exception {
MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
Query query = new Query(where("_id").is(docID).and("itemList.itemID").is(itemID));
mongoOperations.remove(query, Item.class);}
这种方法行不通。但是,当我使用带有$pull方法的BasicDBObject时,它工作得很好!这些方法之间有什么不同!
发布于 2012-04-11 13:36:48
如果你想删除一个数组,我通常使用以下方法:
BasicDBObject match = new BasicDBObject("_id", "1"); // to match your document
BasicDBObject update = new BasicDBObject("itemList", new BasicDBObject("itemID", "1"));
coll.update(match, new BasicDBObject("$pull", update));发布于 2014-03-22 21:17:47
remove方法从模板中删除文档。如果要从数组中删除项,则必须使用pull。就像这样
MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
Query query = new Query(where("_id").is(docID).and("itemList.itemID").is(itemID));
Update update = new Update().pull("itemList", new BasicDBObject("itemID", "1"));
mongoOperations.updateFirst(query, update, Item.class);https://stackoverflow.com/questions/10097621
复制相似问题