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.

Blablalux
  • 485
  • 1
  • 5
  • 9
  • What have you tried, can you put the code in? – Mike Tung Jan 15 '18 at 16:21
  • 1
    You can try `Update update = new Update(); update.pull("preferences", "oranges"); mongoTemplate.updateMulti(new Query(), update, collection_name)` – s7vr Jan 15 '18 at 17:28

1 Answers1

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");
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • 1
    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"); – maslan Feb 06 '19 at 15:09