根据计算出的差异查找 [英] Find based on calculated difference

查看:69
本文介绍了根据计算出的差异查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据一些参数查询我的Mongo数据库.但是,要获取参数,无论如何我首先需要使用find()然后进行一些计算.

I need to query my Mongo DB based on some parameters. However, to get the parameter, I first need to use a find() anyway and then do some calculations.

这显然是无效的.

让我详细说明:

这是我要查询的收藏集:

Here is my collection I want to query:

{
  "title": "1",
  "description": "1",
  "aCounter": 100,
  "bCounter": 20,
  "__v": 0
}

我想查找 aCounter-bCounter 大于 50 的帖子.

我已经准备好模型并准备好一切,但是不知道在find()参数中要放什么.

I have the model and everything ready but don't know about what to put in the find() parameters.

postModel.find({
  //I don't know what to put here
})
.exec(function(err, posts) {
  if(posts){
    //return the data
  }
});

任何输入都会有所帮助.

Any input will help.

谢谢

推荐答案

两个选项:

使用 $where

postModel.find({ "$where": "(this.aCounter - this.bCounter) > 50" })

或实际上更高效的用户将 $redact .aggregate():

or actually more performant to use $redact with .aggregate():

postModel.aggregate([
  { "$redact": {
    "$cond": { 
      "if": {
        "$gt": [
          { "$subtract": [ "$aCounter", "$bCounter" ] },
          50
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

后者要好得多,因为它使用本机编码"运算符,而不是 $where 使用.

The latter is better really because it uses "native coded" operators as opposed to the JavaScript evaluation that $where uses.

尽管有可能,两者都应与常规查询表达式结合使用,因为两者都不能实际使用索引来加快搜索结果的速度.

Where possible though, both should be combined with a regular query expression since neither can actually use an index to speed results on it's own.

这篇关于根据计算出的差异查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆