Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a Subset of Fields from MongoDB in Ruby

I'm trying to get a subset of fields from MongoDB with a query made in Ruby but it doesn't seem to work. It doesn't return any results

This is the ruby code:

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

If I remove the fields hash, it works, returning the results with all the fields

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

Looking at the mongodb console the first query ends-up on the mongodb server like this:

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

If I try to make the query from the mongo client console, it works, I get the results and the subset. I make the query like this:

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

What could be the problem? I've been looking for a solution for this for a couple of hours now.

like image 937
Nick Dima Avatar asked May 25 '11 18:05

Nick Dima


2 Answers

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})
like image 132
Andrew K Avatar answered Sep 22 '22 00:09

Andrew K


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! :\

like image 40
Vladimir Avatar answered Sep 19 '22 00:09

Vladimir