How to find documents where field1 is greater than

2019-09-02 06:32发布

How do you use values from fields in comparison when executing queries?

Example from docs:

db.inventory.find( { qty: { $gt: 20 } } )

How can I use a field value from the document instead of 20, like so:

db.inventory.find( { qty: { $gt: field2 } } )

This is what I am trying to achieve:

var query = model.find();

var first = "field1";
var second = "field2";

query.where(first).gt(second);

Edit: I am building the query dynamicly, so I need to use the query-builder in mongoose.

Edid2: Thanks to the answer below, this is how I solved my problem:

query.where({$where: "this."+first+" > this."+second});

1条回答
Lonely孤独者°
2楼-- · 2019-09-02 07:23

Please try the below query with $WHERE operator :

 db.inventory.find({$where: function() { 
  return ( this.field1 >   this.field2 ); } });

P.S : you can find the $Where documnetation in below link : http://docs.mongodb.org/manual/reference/operator/query/where/

查看更多
登录 后发表回答