5

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!

user2008476
  • 71
  • 2
  • 5

3 Answers3

7

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')
Dave
  • 311
  • 3
  • 4
3

You could use pluck for both of your issues:

  • For plucking two fields at once:

    Model.where(conditions).pluck(:field1, :field2)

  • For plucking a nested field:

    Model.where(conditions).pluck('field.nested_field')


  • Bonus: You could also do this if you want a field and a nested field of some other field:

    Model.where(conditions).pluck(:field1, 'field2.nested_field')

  • And, even this is possible:

    Model.where(conditions).pluck('field.one.two')

    where two is nested field of one which in turn is the nested field of field.

Also, the "field" could be a String, Symbol or Array according to it's documentation: Mongoid::Contextual::Mongo#pluck

Neel
  • 915
  • 6
  • 7
1

Mongoid has a pluck function now.

mongoid#pluck

Example:

Model.where(conditions).pluck(:specific_field)
Mike S
  • 11,329
  • 6
  • 41
  • 76
  • unless you care about duplicates you should use `#distinct` instead of `#pluck` See that question for more: http://stackoverflow.com/q/37333137/2047418 – Filip Bartuzi May 20 '16 at 04:16