2

我需要按两个属性的平均值对查询进行排序,例如Story.scoped.order_by('(importance + points)/2').

正如我在MongoDBOrigin 文档中看到的,这似乎是不可能的。我是否需要使用平均结果创建第三个属性并按其排序?

| Story           | points | importance
| first expected  | 1      | 1
| third expected  | 5      | 1
| second expected | 1      | 3
4

1 回答 1

3

您可以使用聚合框架来执行此操作。我不知道 Ruby/mongoid,但这是你在 JavaScript 中的做法:

db.coll.aggregate([
    { $project: { 
        Story: 1, 
        points: 1, 
        importance: 1, 
        avg: { $divide: [{ $add: ['$points', '$importance']}, 2]}}},
    { $sort: { avg: 1}}
    ], function(err, result){
        console.log(result);
    }
);

输出:

[ { _id: 50a14fcb9f0d79f4de752828,
    Story: 'first expected',
    points: 1,
    importance: 1,
    avg: 1 },
  { _id: 50a14fe59f0d79f4de75282a,
    Story: 'second expected',
    points: 1,
    importance: 3,
    avg: 2 },
  { _id: 50a14fd99f0d79f4de752829,
    Story: 'third expected',
    points: 5,
    importance: 1,
    avg: 3 } ]
于 2012-11-12T19:45:25.660 回答