2

クエリを2つの属性の平均で並べ替える必要がありますStory.scoped.order_by('(importance + points)/2')

MongoDBOriginのドキュメントで見たように、これは不可能のようです。平均的な結果とそれによる順序で3番目の属性を作成する必要がありますか?

| 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 に答える