I'm trying to make a MongoDb script that passes a variable name from an array of variables and then executes a query for that variable:
var continous = ['b', 'e', 'LBE']; //list of variables
continous.forEach(e => izracun(e));
function izracun(atr) {
var query = '{ $group: { _id: "'+atr+'", avg: { $avg: "$'+atr+'" }, stdev: { $stdDevPop: "$'+atr+'" }, nonMissing: { $sum: 1 }}}';
query=JSON.parse(query);
};
The query is constructed as a string, but when I try to JSON.parse it, I get the following error:
[js] uncaught exception: SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data...
Variable "query" has the following value before JSON.parse:
{ $group: { _id: "b", avg: { $avg: "$b" }, stdev: { $stdDevPop: "$b" }, nonMissing: { $sum: 1 }}}
What is wrong here, why do I get that JSON.parse error? I'm planning to use the query inside db.collection.aggregate()