Nerian
Nerian

Reputation: 16177

Sorting on nested attribute, Mongoid

I have a model with this schema:

class Treatment
  include Mongoid::Document

  field :value, type: Money # money-rails gem
end

That value field get saved to the db as value: {"cents"=>313, "currency_iso"=>"EUR"}

I would like find all treatments and sort them by the cents value.

Right now this is how I do it:

Treatment.collection.find().sort({value: { :cents => 1 }})

This is using the Moped driver. How can I do this using plain Mongoid?

Edit1.

  [6] pry(main)> Treatment.all.only(:value).asc('value.cents').entries
  => [#<Treatment _id: 515854c2a1d24ccb1f000005, value: {"cents"=>2849, "currency_iso"=>"EUR"}>,
   #<Treatment _id: 515854c2a1d24ccb1f000006, value: {"cents"=>313, "currency_iso"=>"EUR"}>,
   #<Treatment _id: 515854c2a1d24ccb1f00000f, value: {"cents"=>1214, "currency_iso"=>"EUR"}>,
   #<Treatment _id: 515854c2a1d24ccb1f000010, value: {"cents"=>1795, "currency_iso"=>"EUR"}>,
   #<Treatment _id: 515854c2a1d24ccb1f000011, value: {"cents"=>105, "currency_iso"=>"EUR"}>,
   #<Treatment _id: 515854c2a1d24ccb1f000012, value: {"cents"=>2547, "currency_iso"=>"EUR"}>

Edit2.

mongodb: stable 2.4.1-x86_64 mongoid (3.1.2)

Upvotes: 1

Views: 421

Answers (1)

user324242
user324242

Reputation:

Use the dot syntax:

Treatment.all.asc('value.cents')

edit: Full example:

require 'mongoid'
Mongoid.load!("mongoid.yml", :development)

class Treatment
  include Mongoid::Document
  field :value, type: Hash
end

Treatment.delete_all

15.times do
  Treatment.create(value: {cents: rand(3000), currency_iso: "EUR" })
end
p Treatment.all.only(:value).asc('value.cents').map{|t| t.value["cents"] }

Upvotes: 1

Related Questions