Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pluck multiple and/or nested fields on mongoid

I have the following query db in mongodb that returns exactly what I need:

 db.collection.find({field1: 2801394}, {name: 1, field2: 1, _id: 1, "field3.2801394": 1})

Note field 3 is a hash, and the key used here is the same as for field1 by the value in field 1.

How can I convert this query to mongoid? There are two main issues here, and I can't find anything online for either one individually:

  1. I can't figure out the syntax for both plucking two fields at once
  2. I can't find the syntax for plucking a nested field.

Thanks!

like image 404
user2008476 Avatar asked Jun 06 '13 19:06

user2008476


1 Answers

For filtering out/projecting one or more fields, you can use Queryable.only found at http://mongoid.org/en/origin/docs/options.html.

The example given on that page:

queryable.only(:name, :age)

For nested fields, you could use strings instead of symbols in the parameters:

queryable.only(:name, :field2, :_id, 'field3.2801394')
like image 83
Dave Avatar answered Sep 23 '22 06:09

Dave