0

Suppose I have a collection containing documents like :

{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"]}

Now there are no more oranges so I want to remove them from all documents and end up with :

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

I've been banging my head to know whether, using Spring's mongoTemplate, there is any straightforward way to do this, apart from the obvious (and, I guess, inefficient as the collection is potentially huge) iterative way ? Thanks for your help.

2
  • What have you tried, can you put the code in? Commented Jan 15, 2018 at 16:21
  • 1
    You can try Update update = new Update(); update.pull("preferences", "oranges"); mongoTemplate.updateMulti(new Query(), update, collection_name) Commented Jan 15, 2018 at 17:28

1 Answer 1

1

Something like this will do

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");
Sign up to request clarification or add additional context in comments.

1 Comment

This actually does not work. The elemMatch function can be used only when the array contain objects. When the array contains plain strings it should be Criteria criteria = Criteria.where("preferences").all("oranges");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.