Use the $ lt or $ gt operator in mongodb requests

My collection structure * "countcollection" * looks like below

{ "limitcount": 10000, "currentcount": 100 } 

I want to modify mongoquery to compare currentcount<($lt)limitcount or currentcount>($gt)limitcount .

First I wrote a mongo request as below

 db.countcollection.find({"currentcount":{$lt:{"limitcount"}}}); db.countcollection.find({"currentcount":{$gt:{"limitcount"}}}); 

but he could not fulfill.

Please indicate your contribution for this Mongoka.

early.

javaamtho.

+4
source share
3 answers

As Bugai13 said, you cannot perform a comparison across 2 fields in a query.

The problem with $ where is performance is because it is a javascript function that will be executed for each document, so it will have to scan everything.

So, you can save another field (which you could then index) next to these existing fields

eg.

 { "limitcount": 10000, "currentcount": 100, "remainingcount" : 9900 } 

so that you can request a new field instead:

 db.countcollection.find({"remainingcount" : {$gt : 0}}) db.countcollection.find({"remainingcount" : {$lt : 0}}) 
+5
source

You cannot do what you want using a simple query (for example, you tried above). There is such a mistake in mongodb jira , and you can vote for it.

I assume you are using a javascript expression like this:

 db.countcollection.find( { $where: "this.currentcount < this.limitcount" } ); 

I hope for this help.

+3
source
 $gt:{"limitcount"}} 

makes no sense since you are comparing it with the string limitcount. If you want to compare with a predefined variable, use a variable, but something with quotes around it. Why did you choose this weird syntax?

0
source

Source: https://habr.com/ru/post/1344756/


All Articles