10

我有 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);

}

这种方法行不通。但是,当我将 BasicDBObject 与 $pull 方法一起使用时,它可以正常工作!这些方法有什么区别!

4

2 回答 2

12

如果你想删除一个数组,我通常使用以下内容:

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));
于 2012-04-11T05:36:47.530 回答
5

从模板中删除方法删除文档。如果要从数组中删除项目,则必须使用 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);
于 2014-03-22T13:17:47.473 回答