Find based on calculated difference

安稳与你 提交于 2019-12-25 09:29:08

问题


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.

This, obviously, is not efficient.

Let me elaborate:

Here is my collection I want to query:

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

I want to find posts where aCounter - bCounter is more than 50.

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.

Thanks


回答1:


Two options:

Use $where

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

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

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

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.



来源:https://stackoverflow.com/questions/45116525/find-based-on-calculated-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!