I recently started working with MongoDB and its aggregation pipeline. I need some help with looping over the field called Id
and doing aggregation operation on it one after another directly inside pipeline.
Currently I am doing something like this (in Node.js):
let patients = await client.db('MyDB').collection('Patients_MA').find().toArray();
for (int i=0; i<patients.length; i++)
{
doc = patientColl.aggregate([
{
$match: {Id: patients[i].Id}
},
{
$project: {
_id: 0,
num: {
$add: [
{$multiply: [0.7, 2]},
{$multiply: [0.2, 2]},
{$multiply: [0.15, 0]}
]
}
}
}
]);
await patientsColl.updateOne(
{ "Id": id },
{ "$set": {'heuristic': num} }
);
}
For the sake of easy understanding I have condensed the pipeline to just the main thing I want it to do which is to update the heuristic
value but in my original pipeline, each Id
will have a different heuristic
value. Also, I have approximately 8000 patients Ids and in my original pipeline, I am working with 3 different collection.
So my question is, is there a way to loop over each Id
‘s, run the the pipeline above, and update the heuristic
value directly inside the aggregation pipeline? Or a way to do this more efficiently without having to make O(8000) calls?