Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $where to compare against nested field

I have a mongodb collection with documents of the following structure (simplifying it, the numbers are just for example):

{'a' : 1, 'b' : {'c':2}}

I want to run the following mongodb query:

{'$where' : 'this.a < this.b.c'}

The above doesn't work. What is the correct syntax for such a query ?

like image 674
Baruch Oxman Avatar asked Sep 30 '22 07:09

Baruch Oxman


1 Answers

Found the issue: not all of my collection documents contained the "b" value, and thus I was receiving an error: db.alerts.find({$where:"this.a < this.b.c"}) error: { "$err" : "TypeError: Cannot read property 'c' of undefined", "code" : 16722 }

Fixed by changing my query to: {"b.c":{$exists : true}, $where : "this.c < this.b.c"}

like image 70
Baruch Oxman Avatar answered Oct 08 '22 03:10

Baruch Oxman