How to execute an aggregation from NodeJS that outputs “$out” the results to a collection as the last stage of the aggregation? The aggregation works if I call it from the MongoDB Shell, but I would like to do the same in node.js without it returning the result to the client. I want to result to be sent to another collection in the same database and not to the client application.
The same aggregation should produce the same result.
Have you tried it?
How are the results differ?
I get “in_db.collection(…).aggregate(…).then is not a function” when I try running the sample code below.
async function aggregateBrands(in_db, out_db) {
in_db.collection(‘brands’).aggregate(
[{
“$group”:
{“name”: “$brand_name”,
“brand_id”: {"$addToSet": “$brand_id”},
“count”: {"$sum": 1}
}
},
{ $out: {db:“out_db”, coll:“brand”}}
]).then(result => {
console.log(result)
}).catch(err => {
console.log(err.message)
});
}
If you look at the documentation at Collection | mongodb, you will see that aggregate does not return a Promise but an AggregationCursor.
This means you cannot use then(), hence the error then is not a function. You will need to use one of the method that returns a Promise. In this case, since no documents is output after $out, I am not too sure which one would be a good fit. I would start with tryNext().
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.