Reputation: 2317
I have the following model
class MyModel
field :title, type: String
field :url, type: String
end
I would like to make a query that will return only the title field for each document.
How can I do it?
Upvotes: 0
Views: 141
Reputation: 434665
Use only
or without
:
Queryable#only
Limit the fields that are returned to the provided fields.
Queryable#without
Limit the fields that are returned everything except the provided fields.
So you'd say:
MyModel.query_method_calls.only(:title)
# or
MyModel.query_method_calls.without(:url)
Note that only
will make a mess of things if you're using Mongoid3 with the Identity Map enabled, you'll get half-formed objects stuck in the identity map cache and end up wondering where all the strange nil
attributes are coming from. If this applies to you then bypass Mongoid and use the underlying Moped interface:
Query#select
Select the fields you want returned.
This approach would look like:
MyModel.collection.find(...).select(:title => 1)
You'd be working with hashes instead of Mongoid objects in this case.
Upvotes: 1