Selecting only a subset of keys?

196 Aufrufe
Direkt zur ersten ungelesenen Nachricht

Scotty Weeks

ungelesen,
13.10.2010, 19:46:2713.10.10
an 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

ungelesen,
13.10.2010, 22:07:5613.10.10
an mongo...@googlegroups.com

I believe it should be something like:

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

Jamie Orchard-Hays

ungelesen,
14.10.2010, 00:02:0914.10.10
an 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

ungelesen,
14.10.2010, 13:41:1314.10.10
an 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

ungelesen,
14.10.2010, 13:45:5314.10.10
an 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

ungelesen,
14.10.2010, 13:52:3814.10.10
an 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

ungelesen,
14.10.2010, 15:09:2814.10.10
an 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

ungelesen,
14.10.2010, 16:42:5514.10.10
an mongo...@googlegroups.com
Got it, I was just coming back to post that :)
Allen antworten
Antwort an Autor
Weiterleiten
0 neue Nachrichten