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
=> [
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"}]