This past week or team ran into a rather annoying bug in Mongoid. It seems that Mongoid has issues creating a query that performs a find against a scope created using the _id
field.
Suppose you create a scope like users = User.in(id: array_of_ids)
. If you’re interested in finding a specific user within that scope, you might try a query like users.find(id: user_id)
. However, there’s a problem with this approach. When Mongoid executes the query, the find kills the previous scope and performs a find against the entire collection. Much to our dismay, we found the same issue when using a where
query for the initial scope.
After investigating the query logs, it became evident that Mongoid was doing a merge operation when the _id
field was involved. We found a way to drop down to the driver and manually created a query that used a combination of $and
and $in
. This query allows us to achieve the desired result using Mongoid.
Or conclusion is that in order for Mongoid to respect scope while performing a find, you have to use a scope like this: users = User.and(:[id.in](http://id.in/)=\> array\_of\_ids)
. From that scope, you can then execute the find users.find(id)
.
One of WebVolta’s favorite things is tackling difficult problems. If you’re struggling with your own website, let us know! We’d love to discuss ways that our team might be able to get involved.