Retrieving a Subset of Fields from MongoDB in Ruby Retrieving a Subset of Fields from MongoDB in Ruby ruby ruby

Retrieving a Subset of Fields from MongoDB in Ruby


As of Sep, 2015, these other answers are outdated. You need to use the projection method: #projection(hash)

coll.find({"title" => 'Halo'}).projection({title: 1, isrc: 1})


The query should look like

collection.find(selector = {}, opts = {})

Query the database

In your case it is

coll.find({"title" => 'Halo'}, {:fields => ["title", "isrc"]})

But still remains a problem, the ruby-driver ignores the condition of "fields", and returns all the fields! :\


This query will return only the title and isrc for a doc that has the title "Halo":

coll.find({"title" => 'Halo'},{:fields => {"_id" => 0, "title" => 1, "isrc" => 1}})

Note the use of a Hash for the fields where the keys are the field names and the values are either 1 or 0, depending on whether you want to include or exclude the given field.