Reputation: 1974
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);
})
Upvotes: 0
Views: 529
Reputation: 50406
And you started of with the right concept my constructing something in code, but forgot that JavaScript "stringifies" object keys as well. So there is a different notation for that.
Plus you also not no need $and
here at all:
var queryString0 = 'data.screener.' + req.body.data[0].keyname;
var query = {};
query[querystring0] = { $lt : 200, $gt : 100};
var projection = { name: 1 };
projection[querystring0] = 1;
Company.find(query,projection,function(err,result) {
// work in here
});
So the "bracketed" notation is how you use variable contents as the name of a key. And "all" MongoDB query arguments are "and" conditions anyway, so you would rarely need to wrap them with an $and
, unless you need "two" or more conditions for the same field.
Upvotes: 2