Spring-data-mongodb:mongoTemplate - 从文档集合中的数组中删除元素

时间:2018-01-15 16:19:49

标签: java spring mongodb spring-data-mongodb

假设我有一个包含以下文档的集合:

{name: "a", preferences: ["apples","oranges","bananas"]}    
{name: "b", preferences: ["apricots","oranges","strawberries"]}
{name: "c", preferences: ["oranges","plums"]}
{name: "d", preferences: ["apples","plums","oranges"]}
{name: "e", preferences: ["strawberries","bananas"]}

现在已经没有橙子了,所以我想从所有文档中删除它们,最后得到:

{name: "a", preferences: ["apples","bananas"]}    
{name: "b", preferences: ["apricots","strawberries"]}
{name: "c", preferences: ["plums"]}
{name: "d", preferences: ["apples","plums"]}
{name: "e", preferences: ["strawberries","bananas"]}

我一直想知道,使用 Spring的mongoTemplate ,是否有任何直接的方法可以做到这一点,除了明显的(并且,我猜,效率低,因为集合可能是巨大的迭代方式?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

这样的事情会做

Update update = new Update();
new Update().pull("preferences", "oranges");
Criteria criteria = Criteria.where("preferences").elemMatch(Criteria.where("oranges").exists(true));// Use this if you don't want to do the above update for all documents.

mongoTemplate.updateMulti(new Query(criteria), update, "collection_name");