Im using MongoDB query within JS function. The script looks like this:
var continous = ['b', 'e', 'LBE'];
continous.forEach(e => izracun(e));
function izracun(atr) {
var query1 = { "$match": { [atr]: {"$ne" : -1} } };
var query2 = { "$group": { "_id": atr, "avg": { "$avg": "$"+[atr] }, "stdev": { "$stdDevPop": "$"+[atr] }, "nonMissing": { "$sum": 1 }}};
db.ctg.aggregate([query1, query2]);
}
When I execute it in mongo shell with load("script.js"), the shell returns "true". I tried using the query with fixed parameter values (instead of passing arguments) inside the function, but I still don't get the results (returns "true" only) that should look like example below:
{ "_id" : "b", "avg" : 878.4397930385701, "stdev" : 893.8744489449962, "nonMissing" : 2126 }
If I console log the query and run it directly in mongo shell, it works fine.
What am I doing wrong?
EDIT: I tried handling the promise with:
db.ctg.aggregate([query1, query2]).then(function (results) { //this block will run synchronsly to the aggregate statement
console.log(results);
});
Im getting the following error:
uncaught exception: TypeError: db.ctg.aggregate(...).then is not a function
db.ctg.aggregate([query1, query2])returns a promise. You need to handle the promise via a.then(results => { // Code here }). All-in-all, it looks like:db.ctg.aggregate([query1, query2]).then(results => { // Code here })