How to get one collection field in mongoid / rails?

I have a model

class MyClass
  include Mongoid::Document
  include Mongoid::Timestamps

  field :a, type: String
  field :b, type: String
  field :c, type: String
end

So how to get all a-s, b-s or c-s as a list / array from all objects in the MyClass collection? Does Rails / Ruby / Mongoid have syntactic sugar for this?

I know this can be done:

all_a = []

MyClass.desc(:created_at).each do |my_object|
  all_a.push(my_object.a)
end

But I was thinking about:

MyClass.get(:fields => :a)
MyClass.get(:fields => :a,:b)

Update:

I found something:

MyClass.create(a: "my_a_string")
MyClass.create(a: "my_another_a_string")

Now:

MyClass.only(:a)

should work, but instead I get:

 => #<Mongoid::Criteria
  selector: {}
  options:  {:fields=>{"a"=>1}}
  class:    MyClass
  embedded: false>

When MyClass.only(:a).to_a

 => [#<MyClass _id: 525f3b9e766465194b000000, created_at: nil, updated_at: nil, a: "my_a_string", b: nil, c: nil>, #<MyClass _id: 525f4111766465194b180000, 
created_at: nil, updated_at: nil, a: "my_another_a_string", b: nil, c: nil>]

But I was thinking about:

["my_a_string", "my_another_a_string"]

or

[{a: "my_a_string"}, {a: "my_another_a_string"}]
+4
source share
2 answers

MyClass.only(:a), will return all other fields in the form nil and the selected fields with their values ​​...

You can use instead MyClass.pluck(:a). But you can only pass one field.

If you want more than one field, you can do this:

MyClass.only(:a,:b).map {|obj| [obj.a,obj.b]}
+5

MyClass.distinct(:a) , pluck, , ..

+4

All Articles