对于一个基本的例子,我有一个架构:
var testSchema = new Schema({
op1 : Number,
op2 : Number
});
Run Code Online (Sandbox Code Playgroud)
然后我希望有一个"总计"字段,它不存储在DB中但在检索后自动计算,并且可能用于Mongoose的query.sort.
即
total = op1 + op2
Run Code Online (Sandbox Code Playgroud)
然后用 myTestModel.find({}).sort(total).execFind(...);
这可能吗?
MongoDB不允许您使用普通查询计算字段,但是,您可以使用聚合框架执行此操作.你这样做是这样的:
myTestModel.aggregate(
{ $match: {} }, // your find query
{ $project: {
op1: 1, // original fields
op2: 1,
total: { $add: ['$op1', '$op2' ] } // calculated field
} },
{ $sort: { total: 1 } },
// And then the normal Mongoose stuff:
function (err, res) {
}
);
Run Code Online (Sandbox Code Playgroud)
另见:http://mongoosejs.com/docs/api.html#model_Model.aggregate
| 归档时间: |
|
| 查看次数: |
4332 次 |
| 最近记录: |