Rails & Mongoid - Merging multiple criteria

2019-09-17 10:24发布

问题:

It took me a bit to figure this out and I'm sure others out there are curious how to do this as well..

I have a case where I need to run an .and() query using user input that I converted to an array. My problem was that the query was searching each and every field for BOTH words that was read in from the input.

回答1:

So what I did is broke up the queries based on the fields. I.e. if you have the fields :tags, :story, :author you would have 3 queries, tag_query = Book.any_in(:tags => @user_search)
I created an empty hash conditions = {}
Then I would merge each query to the conditions hash using conditions.merge!(tag_query.selector)

I decided which queries to merge by checking whether the query returned any Book documents: tag_query.exists ? conditions.merge!(tag_query.selector) : nil. If the query returned a Book document it was merged to the hash, if not then nothing happens.

The final step is running the actual query we care about.. @book = Book.where(conditions). Doing this is combining all the queries that actually found something and smashing them together just like an .and() query!

Instead of returning 0 because both words weren't found in each field, this intelligently brings together the fields that actually did find something and makes it so it only counts where both words have been found in the whole document.