Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use $lt or $gt operator in mongodb queries

Tags:

mongodb

My collection structure*"countcollection"* is looks as below

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

I want to right the mongoquery that able to compare the currentcount<($lt)limitcount or currentcount>($gt)limitcount.

First, i wrote the mongo query as below

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

but it's failed to execute .

please give your input for this mongoquery.

thanks in advance .

javaamtho.

like image 211
javaamtho Avatar asked Feb 24 '23 17:02

javaamtho


1 Answers

As Bugai13 said, you can't do a comparison on 2 fields in a query.

The problem with $where is performance - as that is a javascript function that will be executed for every document so it will have to scan through every one.

So, you could store another field (that you could then index) alongside those existing fields

e.g.

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

so you could then query on the new field instead:

db.countcollection.find({"remainingcount" : {$gt : 0}})
db.countcollection.find({"remainingcount" : {$lt : 0}})
like image 190
AdaTheDev Avatar answered Mar 05 '23 16:03

AdaTheDev