I am trying to do something rather simple I believe:
1) insert a value in an array field only if that value is not already present
2) remove a value if it exists in the array
I have just no idea how to do any of this things... for the moment I am just inserting my value without checking if it exists already: myArray << obj.id
Thanks,
Alex
ps: using Rails 3.0.3, mongo 1.1.5 and mongoid 2.0.0.rc5
ps2: this is the mongodb syntax to achieve what I want, but I have no idea how to do this in mongoid
{ $addToSet : { field : value } }
Adds value to the array only if its not in the array already, if field is an existing array, otherwise sets field to the array value if field is not present. If field is present but is not an array, an error condition is raised.
To add many valuest.update
{ $addToSet : { a : { $each : [ 3 , 5 , 6 ] } } }
$pop
{ $pop : { field : 1 } }
removes the last element in an array (ADDED in 1.1)
{ $pop : { field : -1 } }
removes the first element in an array (ADDED in 1.1) |