Remove all objects matching condition from an array


#1

I want to remove all objects with the same country from the array but my query removes only one each execution.

  "notifications": [{
  "text": "werwe",
  "seller": "2323",
  "country": "GB"
  }, {
  "text": "we232323e",
  "seller": "132333",
  "country": "GB"
  }, {
  "text": "xcvx cxx",
  "seller": "6344323",
  "country": "FR"
  }]

query:

UPDATE bucket USE KEYS "test_key"
SET notifications = ARRAY_REMOVE(notifications, i) FOR i IN notifications WHEN i.country = "GB" END;

#2

SET notifications = ARRAY_REMOVE(notifications, i) FOR i IN notifications WHEN i.country = “GB” END;
ARRAY_REMOVE(notifications, i) – notifications is original element not intermediate results.

You should use array construct to build new array and assign it.

You want mutate documents when notifications has at least one country of “GB” (controlled by WHERE caluse) and remove them (controlled by SET clause).

UPDATE bucket USE KEYS "test_key" 
SET notifications =   ARRAY v  FOR v IN notifications WHEN v.country  != "GB" END
WHERE ANY v IN notifications SATISFIES v.country = "GB" END;

#3

What if I want to have more conditions and I just want to delete those that match condition and leave the rest? if I add more conditions then it deletes everything


#4

Add them to SATISFIES and WHEN clause.


#5

Yes I added to SATISFIES AND WHEN ( conditionA AND conditionB AND conditionC ) but even if one of them is true then it deletes from array


#6

Please note WHEN condition must be negative of WHERE . If still need help please post original query.

UPDATE bucket USE KEYS "test_key" 
SET notifications =   ARRAY v  FOR v IN notifications WHEN  NOT (v.country  = "GB"  AND v.seller = "132333")  END
WHERE ANY v IN notifications SATISFIES v.country = "GB" AND v.seller = "132333" END;

Try following select and adjust your conditions and play around before you do actual update.

SELECT  ARRAY v  FOR v IN notifications WHEN  NOT (v.country  = "GB"  AND v.seller = "132333")  END
FROM   bucket USE KEYS "test_key" 
 WHERE ANY v IN notifications SATISFIES v.country = "GB" AND v.seller = "132333" END;