问题
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