1

I have a webpage where users selects variables to filter and get database values. I tried passing the $match condition variables as below but i am not getting any results back

URL is : example.com?gender=M&date_from=20100101&date_to=201140101

I loop through the req.query to build the match condition string.

var matchQuery = [];
for (var param in req.query) {
    qString = "{'" + param + "' : '" + req.query[param] + "'}";
    matchQuery.push(qString);              
}
var strmatchQuery = matchQuery.toString();

This outputs strmatchQuery as {'gender' : 'M'}, {'date_from' : '20100101'}, {'date_to' : '20140101'}

and then I call the mongodb aggregate function

dbmodel.aggregate( { $match: { $and: [ strmatchQuery ]} } , { $group : { _id : "$orderyear", totalorders : { $sum : 1 } } } )

But I dont get any results back. Any ideas?

1 Answer 1

3
function is_numeric(num) {
    return !isNaN(num);
}

var matchQuery = [];
var qString = {};
for (var param in req.query) {
    // You need objects in your query not strings so push objects
    qString = {};
    qString[param] = is_numeric(req.query[param]) ? Number(req.query[param]) : req.query[param];
    matchQuery.push(qString);              
}

// Removed the toString() function call

dbmodel.aggregate(
    {$match: {$and: strmatchQuery}}, // Removed the array [ ] 
    {$group: {
        _id: "$orderyear",
        totalorders: {$sum: 1}}
    }
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It mostly works. It works when query is a string field, but date_from and date_to are numeric in my database, I guess thats causing it null result. How can I set the object value to numeric?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.