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 the a
-s, b
-s or c
-s as a list/array from all objects in the MyClass collection? Does Rails/Ruby/Mongoid have any syntactic sugar for this?
I know, it is possible to do so:
all_a = []
MyClass.desc(:created_at).each do |my_object|
all_a.push(my_object.a)
end
But I thought about:
MyClass.get(:fields => :a)
MyClass.get(:fields => :a,:b)
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 thought about:
["my_a_string", "my_another_a_string"]
or
[{a: "my_a_string"}, {a: "my_another_a_string"}]
MyClass.only(:a)
, will return every other field as nil, and the selected fields with their values...
You can use MyClass.pluck(:a)
instead.
But you can pass only one field.
If you want more than one field, you can do this:
MyClass.only(:a,:b).map {|obj| [obj.a,obj.b]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With