I was looking for a simple way to add tagging to my Mongoid 3+ models and most of the options I found were for Mongoid 2 only. Luckily I stumbled upon Mongoid Simple Tags from Mauro Torres(chebyte) a ruby gem that supports Mongoid 3+.
Its a nice simple way to add tagging. Simply include “Mongoid::Document::Taggable” to your model.
1 2 3 4
Once added you can assign tags through the #tag_list= method. This assumes a string of comma seperated tags, which are then stored in the tags field as an array.
You can retrieve back comma seperated list of tags with the #tag_list method or an array of tags on the object with the #tags method.
Mongoid-simple-tags provides a way to search for instances with a tag via the ::tagged_with method. This can either be given a single tag or an array of tags. In the later case it will return all instance that have any of the given tags. Unfortunately there is not currently a method to search for instances matching all tags in an array.
You can also get a list of all tags used on a model with there associated counts, with the ::all_tags method. This is accomplished using MongoDb’s map-reduce functions.
1 2 3
Lastly, if you simply would like an array of all tags used on instances of a model there is the ::tag_list method.