如何查找field1大于field2的文档? (Nodejs/猫鼬/MongoDB)
在执行查询时如何在比较中使用字段中的值?
How do you use values from fields in comparison when executing queries?
文档示例:
db.inventory.find( { qty: { $gt: 20 } } )
如何使用文档中的字段值而不是20,就像这样:
How can I use a field value from the document instead of 20, like so:
db.inventory.find( { qty: { $gt: field2 } } )
这是我要实现的目标:
var query = model.find();
var first = "field1";
var second = "field2";
query.where(first).gt(second);
我正在动态地构建查询,所以我需要在猫鼬中使用查询生成器.
I am building the query dynamicly, so I need to use the query-builder in mongoose.
Edid2:感谢下面的回答,这就是我解决问题的方法:
Edid2: Thanks to the answer below, this is how I solved my problem:
query.where({$where: "this."+first+" > this."+second});
请使用$ WHERE运算符尝试以下查询:
Please try the below query with $WHERE operator :
db.inventory.find({$where: function() {
return ( this.field1 > this.field2 ); } });
P.S:您可以在下面的链接中找到$ Where文档: http://docs.mongodb.org/manual/reference/operator/query/哪里/
P.S : you can find the $Where documnetation in below link : http://docs.mongodb.org/manual/reference/operator/query/where/