Reputation: 1547
I'm build a Rails application with Mongoid and I need tags in one of my models.
class Question
include Mongoid::Document
include Mongoid::Timestamps
has_many :options
belongs_to :user
field :title, type: String
field :options_count, type: Fixnum, default: 0
field :tags, type: Array
end
It works well and I can get all Question's tags using any_in
Question.any_in(tags:'foo')
But how can I get all tags from all documents in Question?
I'm trying to use map/reduce but it looks like I'm just sweeping all documents and treating the arrays in Ruby and it just doesn't feel right.
map = %Q{
function() {
emit(this.title, {tags: this.tags});
}
}
reduce = %Q{
function(key, values) {
var result = [];
values.forEach(function(value) {
result.push(value.tags);
});
return result.toString();
}
}
map_reduce(map, reduce).out(inline: true).each do |doc|
p doc['value']
end
Upvotes: 2
Views: 155
Reputation: 14572
You can use db.collection.distinct
for this. In your case, using Mongoid:
Question.distinct(:tags)
This will return an array of all tags in all documents with no repeated values.
Upvotes: 1