MongoDB 查询是否(字段 A - 字段 B)> N

MongoDB Query if (Field A - Field B) > N

我已经被困在这个问题上好几个小时了。我需要编写一个查询 returns all documents where (Field A - Field B) > N

// sample data
{ _id: '...', estimated_hours: 0, actual_hours: 0 },
{ _id: '...', estimated_hours: 10, actual_hours: 9 },
{ _id: '...', estimated_hours: 20, actual_hours: 30 }

借用 this stack question 的答案我写了下面的内容,在我看来这应该有效,但是我一直在取回与查询不匹配的记录...

## Attempt 1
n = 0
records = API::Record.where('$where': "(this.estimated_hours - this.actual_hours) > #{n}")
## should return the following, but im getting additional records
#=> [{ _id: '...', estimated_hours: 10, actual_hours: 9 }]

我知道我可能可以使用 $project 完成此操作,但是我必须明确告诉 $project 我想要返回哪些字段。我需要返回所有字段,我们使用处理分页的第三方库

play

db.collection.find({
  $where: "(this.estimated_hours - this.actual_hours) > 1"
})

Similar example for reference