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);
いいえ、を使用して計算列を作成することはできません。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);
});