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) |
You want to use the add_to_set
method, as documented (somewhat) here: http://mongoid.org/en/mongoid/docs/persistence.html#atomic
Example:
model = Model.new
model.add_to_set(:field, value)
model.save
You can give it a single value or even an array of values. The latter will use mongo's $each
qualifier along with $addToSet
when adding each element of your array to the field you specify.
As per Chris Hawk from Mongoid googlegroup:
Arrays in Mongoid documents are simple Ruby arrays. See the docs for the Array class: http://www.ruby-doc.org/core/classes/Array.html
So, for insertion you can simply do:
array << object unless array.include?(object)
And for removal:
array.delete(object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With