I'm using the MongoDB $and in combination with $lt and $gt like this:
var queryString0 = 'data.' + req.body.data[0].keyname;
console.log(queryString0);
//Prints 'data.price'
Company.find({ $and : [{ queryString0 : { $lt : 200, $gt : 100}}]}, {name: 1, queryString0 : 1} , function(err, result) {
if (err) {
throw err;
}
res.send(result);
});
The problem is that this gives me no results while I use the queryString0 to retrieve the data, however, it gives me the desired results if I use a static string like this:
var queryString0 = 'data.screener.' + req.body.data[0].keyname;
console.log(queryString0);
//Prints 'data.price'
Company.find({ $and : [{ 'data.price' : { $lt : 200, $gt : 100}}]}, {name: 1, 'data.price' : 1} , function(err, result) {
if (err) {
throw err;
}
res.send(result);
});
This doesn't make any sense to me, as the same query-string should be provided in both cases.
Please help me figuring out what is wrong with my code.
EDIT: The reason I used $and is because I will also need to check if several fields match my other conditions, like this:
var queryString0 = 'data.screener.' +req.body.data[0].keyname;
var queryString1 = 'data.screener.' +req.body.data[1].keyname;
Company.find({ $and : [
{queryString0 : {$lt : req.body.data[0]["max"], $gt : req.body.data[0]["min"]}},
{queryString1 : {$lt : req.body.data[1]["max"], $gt : req.body.data[1]["min"]}}
] },{ name : 1, queryString0 : 1, _id : 0 }, function(err, result) {
if (err) {
throw err;
}
res.send(result);
})
$andwhen you only have one filter criteria in the array you assign to it?$andrather than accept that all conditions are "and" arguments anyway, and yet have no problems writing{ $gt: 100, $lt: 200 }which is in itself "yet another form of implicit and", as multiple arguments to the "right" of the key means exactly that.