我有一个网页,用户可以选择要过滤的变量并获取数据库值。我尝试传递$ match条件变量,如下所示,但我没有得到任何结果
网址为:example.com?gender=M&date_from=20100101&date_to=201140101
我遍历req.query来构建匹配条件字符串。
var matchQuery = [];
for (var param in req.query) {
qString = "{'" + param + "' : '" + req.query[param] + "'}";
matchQuery.push(qString);
}
var strmatchQuery = matchQuery.toString();
这会将strmatchQuery输出为{'gender':'M'},{'date_from':'20100101'},{'date_to':'20140101'}
然后我调用mongodb聚合函数
dbmodel.aggregate( { $match: { $and: [ strmatchQuery ]} } , { $group : { _id : "$orderyear", totalorders : { $sum : 1 } } } )
但我没有得到任何结果。有什么想法吗?
答案 0 :(得分:2)
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}}
}
);