Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return only fields that are needed in Mongoid?

How do I perform a query that doesn't return the entire document, but only fields that I have specified?

like image 662
Jeremy Smith Avatar asked Oct 12 '11 15:10

Jeremy Smith


2 Answers

From the horse's mouth:

# Return only the first and last names of each person.
  Person.only(:first_name, :last_name)

Source: http://mongoid.org/docs/querying/criteria.html#only

like image 89
Srdjan Pejic Avatar answered Nov 01 '22 03:11

Srdjan Pejic


you can also use pluck

Person.all.pluck(:first_name, :last_name, :id)

http://www.rubydoc.info/github/mongoid/mongoid/Mongoid%2FContextual%2FMongo%3Apluck

like image 24
Jan Avatar answered Nov 01 '22 03:11

Jan