Mongoose查询比较字段值
假设我有以下计划
TestSchema{ val1:Number, val2:Number}
是否有可能写一个查询所有返回的结果是哪里val1 = val2?
如果是这样,有没有办法使用它时,填充? (也许在opts对象的匹配字段内?)
我想你想要的是$ where操作符 。 使用它你至less可以返回这些字段匹配的元素。
例如:db.myCollection.find(“this.val2 == this.val2”);
我现在不能在这个地方进行testing,所以你可能需要玩一下,但是这会让你开始。
我也应该提到,在使用$的地方有一个显着的性能问题,所以谨慎使用。
你可以用$where
操作符来做到这一点。
TestModel.find({ $where: 'this.val1 <= this.val2' }). exec(function(err, results) { // results here });
你也可以把一个函数传给$where
来处理结果。
正如克里斯所说,这是一个昂贵的操作,因此在部署到生产之前先testing它的工作原理。
你可以用aggregate
来做到这一点:
Test.aggregate([ // Add a field to each doc that indicates if the two fields match {$project: { val1: 1, val2: 2, isMatch: {$eq: ['$val1', '$val2']} }}, // Filter to just those docs where they match {$match: {isMatch: true}}, // Remove isMatch to get back the original doc {$project: { val1: 1, val2: 1 }} ], callback);
你不能这样做来比较填充结果中的字段,只有被查询的集合。
这应该比使用$where
更快。