Pluck multiple and/or nested fields on mongoid
Asked Answered
W

3

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!

Wargo answered 6/6, 2013 at 19:54 Comment(0)
C
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')
Catfall answered 29/7, 2013 at 0:45 Comment(0)
G
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

Garboil answered 29/3, 2018 at 22:37 Comment(0)
S
1

Mongoid has a pluck function now.

mongoid#pluck

Example:

Model.where(conditions).pluck(:specific_field)
Shoebill answered 5/3, 2015 at 16:38 Comment(1)
unless you care about duplicates you should use #distinct instead of #pluck See that question for more: https://mcmap.net/q/2029899/-pluck-vs-distinct-in-mongoid-db-which-is-faster/2047418Suitcase

© 2022 - 2024 — McMap. All rights reserved.