I'm trying to make something pretty simple, I believe:
1) insert the value in the array field only if this value is not already specified
2) delete the value if it exists in the array
I just donβt know how to do this ... at the moment I am just inserting my value without checking if it already exists: myArray <<obj.id
Thanks,
Alex
ps: using Rails 3.0.3, mongo 1.1.5 and mongoid 2.0.0.rc5
ps2: this is mongodb syntax to achieve what I want, but I have no idea how to do this in mongoid
{ $addToSet : { field : value } }
Adds a value to the array only if it is no longer in the array, if the field is an existing array, otherwise it sets the field for the value of the array if the field is absent. If the field is present but not an array, an error condition occurs.
To add a lot of valueest.update
{ $addToSet : { a : { $each : [ 3 , 5 , 6 ] } } } $pop { $pop : { field : 1 } }
deletes the last element in the array (added in 1.1)
{ $pop : { field : -1 } }
removes the first element in an array (ADDED in 1.1) |
Alex
source share