Reputation: 73
I have a collection called Example, all the fields of a collection are dynamic. I want to perform a common search. I have no idea how I can do. For example, if I search for "hello" it should return all the objects of a collection which contains name irrespective of the fields the value contained.
Example:
{ id: 111234, desc: 'hello world' },
{ id: 545ttt, title: 'hello title' },
{ id: sfsd3, data: 'hello' }
My query should return all the above records if I search for hello. I found a mongoid_search gem but I did not find anything related to dynamic fields search.
Thanks in Advance.
Upvotes: 0
Views: 325
Reputation: 1573
You can also create a "virtual field" that contains concatenated content of all string fields. Then use this with the mongoid_search:
search_in :search_data
def search_data
self.attributes.select{|k,v| v.is_a?(String) }.values.join(' ')
end
How this works: The mongoid_search
gem runs the search_data
method before each save and uses it's output to fill the (hidden) _keywords
field. This field is then used for the actual search when you're doing something like YourModel.full_text_search('hello')
.
Upvotes: 1
Reputation: 3185
Step 1. Create a text index on all fields.
db.collection.createIndex({ "$**": "text" },{ name: "TextIndex" })
Step 2. You can do a simple text search with $text as following query object:
{ $text : { $search: <your string> } }
Upvotes: 3