我有一个使用此架构的模型:
class Treatment
include Mongoid::Document
field :value, type: Money # money-rails gem
end
该值字段以value: {"cents"=>313, "currency_iso"=>"EUR"}
我想查找所有处理方法并按cents
值对其进行排序。
现在我就是这样做的:
Treatment.collection.find().sort({value: { :cents => 1 }})
这是使用Moped驱动程序。我怎么能用普通的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:稳定2.4.1-x86_64 mongoid(3.1.2)
答案 0 :(得分:1)
使用点语法:
Treatment.all.asc('value.cents')
修改强> 完整的例子:
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"] }