1

在 MySQL 中,可以在 where 子句中的字段上应用本机函数。例如。

SELECT * FROM t WHERE DATE(the_date) < '2012-11-19';

或者

SELECT * FROM t WHERE a+b < 20;

现在,是否可以在猫鼬查询的条件字段上使用函数?假设我正在查询这样的内容:

tSchema.find({a+b: {$lt: 20}}, callback);
4

1 回答 1

2

不,您不能使用 来创建计算列find,因此您必须使用aggregate更灵活但也更慢的方法。

像这样:

tSchema.aggregate([

    // Include the a, b, and a+b fields from each doc
    { $project: {
        a: 1,
        b: 1,
        sum: {$add: ['$a', '$b']}}},

    // Filter the docs to just those where sum < 20
    { $match: {sum: {$lt: 20}}}

], function(err, result) {
    console.log(result);
});

为了完整起见,我应该注意您可以find使用$where过滤器来执行此操作,但是它的性能很糟糕,因此不推荐使用。像这样:

tSchema.find({$where: 'this.a + this.b < 20'}, function(err, result) {
    console.log(result);
});
于 2012-11-19T14:08:49.153 回答