Mongoid - Array management ? insert unique value, remove value if exists?

By : Alex
Source: Stackoverflow.com
Question!

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) |

By : Alex


Answers

worth mentioning, in mongoid, as of 2.0.0pre4 I do not see any addToSet support. mongo_mapper (while imo less maintained :( ) supports this via push_uniq method.

short of that, in mongoid, if you are working with the relationship method directly, you don't need to do the include?. if you are working with the array directly, you do.

Example:

class Person
   include Mongoid::Document
   has_and_belongs_to_many :pets ## or has_many :pets, :stored_as =
By : spotman


This video can help you solving your question :)
By: admin