javaamtho
javaamtho

Reputation: 382

use $lt or $gt operator in mongodb queries

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.

Upvotes: 4

Views: 3176

Answers (3)

AdaTheDev
AdaTheDev

Reputation: 147234

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}})

Upvotes: 5

Andrew Orsich
Andrew Orsich

Reputation: 53685

You can't do what you want using simple query(like you have tried above). There is such bug in mongodb jira and you can vote up for this.

I suppose you shoud use javascript expression like this:

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

Hope this help.

Upvotes: 3

user2665694
user2665694

Reputation:

$gt:{"limitcount"}}

does not make any sense since you are comparing against the string limitcount. If you want to compare against a pre-defined variable, use the variable but something with quotes around it. Why did you choose this strange syntax?

Upvotes: 0

Related Questions