I have a collection of users who store their favorite stuff id’s in an array, like this:

2.3-head :212 > User.each{ |u| puts u.inspect }
 => #<User _id: BSON::ObjectId('587356c45973747b77f1a35c'), favorite_ids: [1, 3, 5]>
 => #<User _id: BSON::ObjectId('587356c45973747b77f1a35d'), favorite_ids: [7, 3, 5, 2, 8]>
 => #<User _id: BSON::ObjectId('587356c45973747b77f1a35e'), favorite_ids: [3, 2, 7]>
 => #<User _id: BSON::ObjectId('587356c45973747b77f1a35f'), favorite_ids: [1, 10]>

I want to find those users who have favorited items 2, 3 and 8, and get them sorted by number of matchings.

class User
  def self.find_matches(array)
    User.collection.aggregate([
      { "$match" => { favorite_ids: { "$in" => array } } },
      { "$unwind" => "$favorite_ids" },
      { "$match" => { favorite_ids: { "$in" => array } } },
      { "$group" => { _id: "$_id", match_count: { "$sum" =>1 } } },
      { "$sort" => { match_count: -1 } }
    ])
  end
end

Finally:

2.3-head :228 >   User.find_matches([2,3,8]).entries
 => [{"_id"=>BSON::ObjectId('587356c45973747b77f1a35d'), "match_count"=>3}, {"_id"=>BSON::ObjectId('587356c45973747b77f1a35e'), "match_count"=>2}, {"_id"=>BSON::ObjectId('587356c45973747b77f1a35c'), "match_count"=>1}]