Getting a subset of fields from MongoDB in Ruby

I am trying to get a subset of fields from MongoDB with a query made in Ruby, but it does not work. It does not return any results.

This is the ruby ​​code:

coll.find("title" => 'Halo', :fields => ["title", "isrc"]) #this doesn't work 

If I delete field hashes, it works by returning results with all fields

 coll.find("title" => 'Halo') #this works 

Looking at the mongodb console, the first request ends on the mongodb server as follows:

 { title: "Halo", fields: [ "title", "isrc" ] } 

If I try to make a request from the mongo client console, it works, I get the results and a subset. I am making a request as follows:

 db.tracks.find({title: 'Halo'}, {title:1,isrc:1}) 

What could be the problem? I have been looking for a solution for this for several hours.

+8
ruby mongodb subset
source share
4 answers

The request should look like

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

Request a database

In your case, this is

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

But there is still a problem, the ruby ​​driver ignores the "field" condition and returns all the fields !: \

+11
source share

This query will only return the header and isrc for the document that has the "Halo" header:

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

Pay attention to the use of the hash for fields where the keys are field names and the values ​​are 1 or 0, depending on whether you want to include or exclude this field.

+10
source share

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

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

You can use the following query

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

if you do not want _id to be received in the case.

+2
source share

All Articles