3

I have many functions update with mongo

here is an example :

 db.auto.update({'def.name':'AFFAIRES'},{$push:{
"covers":{$each: [{"a":'G06'},{"a":'G07'},{"a":'G03'},{"a":'G04'},{"a":'G07'},{"a":'G30'},{"a":'G34'},
{"cover":'G14'}]}}},{multi:true})

But,the problem, my collection may contain one of these variables "a", so i don't need to push it, and if it doesn't, i have to push it in the collection. So my question is how to tell mongoDB to verify before the push, is it possible?? My query may contain other variables to push also.

chou
  • 253
  • 3
  • 14
  • Have you tried [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-option) option? – G07cha Aug 30 '16 at 10:18
  • No, because what i know about upsert : it push the element if it didn't find the query 'update' – chou Aug 30 '16 at 10:25

1 Answers1

7

Use $addToSet - The $addToSet operator adds a value to an array unless the value is already present. If the value is already present then the $addToSet does nothing to that array. $addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.

Clement Amarnath
  • 5,301
  • 1
  • 21
  • 34