Mongodb - 使用多个字段进行ROR排序

时间:2011-10-17 07:33:43

标签: ruby-on-rails sorting mongodb mongoid

我正在使用mongoDB数据库在rails上开发一个ruby站点。我是mongoDB的初学者,我想使用多个键对数据进行排序。我的一个系列如下所示。

dd_users
{
   "_id": ObjectId("4e9bcbdb1d41c866c600004e"),   
   "name": "Ram",
   "score":5
    "created_at": ISODate("2011-10-17T06: 31: 55.0Z"),
}
{
   "_id": ObjectId("4e9bcbdb1d41c866c600004f"),   
   "name": "Robert",
   "score":1
   "created_at": ISODate("2011-10-12T06: 31: 55.0Z"),
}
{
   "_id": ObjectId("4e9bcbdb1d41c866c600004g"),   
   "name": "Molly Bracken",
   "score":3
   "created_at": ISODate("2011-10-15T06: 31: 55.0Z"),
}
{
   "_id": ObjectId("4e9bcbdb1d41c866c600005k"),   
   "name": "Ninou-Co France",
   "score":5
   "created_at": ISODate("2011-10-16T06: 31: 55.0Z"),
}

我想按照“得分”和“created_at”的降序对记录进行排序。 我使用mongomapper查询作为 1.DdUser.where({“name”=> {“$ ne”=> nil})。sort([[“score”,“desc”],[“created_at”,“desc”]])。但我只得到了得分的结果。

我期待结果

{
   "_id": ObjectId("4e9bcbdb1d41c866c600004e"),   
   "name": "Ram",
   "score":5
    "created_at": ISODate("2011-10-17T06: 31: 55.0Z"),
}
{
   "_id": ObjectId("4e9bcbdb1d41c866c600005k"),   
   "name": "Ninou-Co France",
   "score":5
   "created_at": ISODate("2011-10-16T06: 31: 55.0Z"),
}
{
   "_id": ObjectId("4e9bcbdb1d41c866c600004g"),   
   "name": "Molly Bracken",
   "score":3
   "created_at": ISODate("2011-10-15T06: 31: 55.0Z"),
}
{
   "_id": ObjectId("4e9bcbdb1d41c866c600004f"),   
   "name": "Robert",
   "score":1
   "created_at": ISODate("2011-10-12T06: 31: 55.0Z"),
}

3 个答案:

答案 0 :(得分:3)

DdUser.where("name" => { "$ne" => nil } ).sort(["score","desc"], ["created_at","desc"])

答案 1 :(得分:0)

我个人没有使用Mongomapper,因此以下代码未经测试:

DdUser.where("name" => { "$ne" => nil } ).sort([:score.desc, :created_at.desc])

答案 2 :(得分:0)

对我来说有用的是

DdUser.where("name" => { "$ne" => nil } ).sort(:score.desc, :created_at.desc)