您可以使用聚合框架来执行此操作。我不知道 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 } ]