Selecting only a subset of keys?

196 views
Skip to first unread message

Scotty Weeks

unread,
Oct 13, 2010, 7:46:27 PM10/13/10
to mongo...@googlegroups.com
I'm sure I'm missing something obvious but I can't for the life of me figure out how to just get a subset of fields back, e.g. the equivalent to

> db.collection.find({"_id": ObjectId}, { "name": 1, "slug": 1})

When I do:

> Profile.all(:id => ObjectId, :fields => [:name, :slug])

I get the entire profile object back.

So, how do I do this?

Thanks,
Scotty Weeks

Randy Schmidt

unread,
Oct 13, 2010, 10:07:56 PM10/13/10
to mongo...@googlegroups.com

I believe it should be something like:

> Profile.fields([:name, :slug]).all(:id => ObjectId)

Jamie Orchard-Hays

unread,
Oct 14, 2010, 12:02:09 AM10/14/10
to mongo...@googlegroups.com
I don't think you need to put it in an array, just list the fields, but that's the right syntax with Plucky.

> --
> You received this message because you are subscribed to the Google
> Groups "MongoMapper" group.
> For more options, visit this group at
> http://groups.google.com/group/mongomapper?hl=en?hl=en

Scotty Weeks

unread,
Oct 14, 2010, 1:41:13 PM10/14/10
to mongo...@googlegroups.com
Interesting, this doesn't seem to work for me at all, I always get the entire object back. (Both with splat syntax and with passing an array)

Scotty Weeks

unread,
Oct 14, 2010, 1:45:53 PM10/14/10
to mongo...@googlegroups.com
Actually, on closer look it seems like it's handing back all of the keys, but not any of the embedded documents, it doesn't seem to matter what args I pass to the #fields method.


On Oct 14, 2010, at 12:02 AM, Jamie Orchard-Hays wrote:

Jamie Orchard-Hays

unread,
Oct 14, 2010, 1:52:38 PM10/14/10
to mongo...@googlegroups.com
I made the same mistake too. What is going on is that it retrieves only the data you ask for, but since your fields are defined in your model (key :blah) you get empty/default values for those attributes in each instance of the model.

John Nunemaker

unread,
Oct 14, 2010, 3:09:28 PM10/14/10
to mongo...@googlegroups.com
Yes. This is confusing at first. If you look at the query, the fields are in fact not returned, but so to the model instance they just appear nil or as the default. We might want to look at keeping track of loaded keys on a per instance basis so that this can be more obvious. I'll make a note.

Scotty Weeks

unread,
Oct 14, 2010, 4:42:55 PM10/14/10
to mongo...@googlegroups.com
Got it, I was just coming back to post that :)
Reply all
Reply to author
Forward
0 new messages