My .js script reads from a file containing mongodb queries and populates it into an array. Then I read that array and executing the queries but they are not being executed. Below is my code.
1. //After successfuly connecting to mongodb
2. //read a file containing queries
3. var queryFile = cat("queries.txt");
4. var queries = queryFile.split("\r\n");
5. var length = queries.length;
6. for(var i = 0; i < length; i++){
7. var start = new Date().getTime()
8. queries[i]
9. var end = new Date().getTime();
10. var timeElapsed = (end - start)/1000;
11. print ( "Time taken to run query : "+timeElapsed+" secs" )
12. }
It only works if I replace line 12 with an actual query e.g. db.coll.count()
queries[i]
is just a string. It's a stringified instruction. My guess would be to evaluate it with eval(queries[i])
.
for(var i = 0; i < length; i++){
var start = new Date().getTime()
eval(queries[i]);
var end = new Date().getTime();
var timeElapsed = (end - start)/1000;
print ( "Time taken to run query : "+timeElapsed+" secs" )
}
However, one often says that eval is evil and has to be used ONLY in last resort.