Jeremy Smith
Jeremy Smith

Reputation: 15069

Performing an OR of two Mongoid "any_in" queries

If I have two queries that look like:

Store.any_in(:store_id => @user.stores_followed)
Store.any_in(:store_id => @category.stores)

How do I join these into an OR using any_of? I tried this and it doesn't. I tried

Store.any_of({:store_id.any_in => @user.stores_followed}, 
  {:store_id.any_in => @category.stores})

Upvotes: 5

Views: 2748

Answers (3)

Jesse Clark
Jesse Clark

Reputation: 1200

You pass an $or query an array of $in conditions like so:

Store.or( { :store_id.in => @user.stores_followed }, { :store_id.in => @category.stores } )

Upvotes: 5

Simone Carletti
Simone Carletti

Reputation: 176352

any_in accepts an array of OR values using the $in operator.

ids = @user.stores_followed.map(&:id) + @category.stores.map(&:id)
Store.any_in(:store_id => ids)

Upvotes: 1

Jeremy Smith
Jeremy Smith

Reputation: 15069

It looks like it isn't full supported in Mongoid, so I had to do:

Store.any_of({"store_id" => { "$in" => @user.stores_followed}}, {"store_id" => 
   {"$in" => (:store_id => @category.stores)}})

Upvotes: 7

Related Questions