Thank you very much for your reply, we have create a POST collection for post contents, then we have an PostActivity collection which holds both comments and likes. I am trying to create an aggregate view to total comments and likes for the post; by grouping and then doing merge on it. See the example below
https://docs.mongodb.com/manual/core/materialized-views/
we are following similar logic to create the aggregation, but the problem we are having is that first time it aggregates fine, but when we try to run it periodically using scheduler, then as shown above in the document, it should only take new records and update the old one, the above example shows exactly that, it add up the new record sum in the aggregate view rather than just replacing it with new sum for existing grouping. For some reason, when I do this kind of grouping on PostId, this method doesn’t add to the result rather replaces it completely with only newly found group sum. But when I use the data wise grouping as shown in the example above, then it works as expected. Here is my function which is doing aggregation:
exports = async function() {
const mongodb = context.services.get("Cluster0");
const collection = mongodb.db("test").collection("PostActivity");
// getting last run datetime
var lastDate = await context.functions.execute("getPostAggregateHistory");
var currDate = new Date();
console.log(`executing aggregatePost with LastRunDateTime: ${lastDate.LastRunDateTime}.`);
return collection.aggregate( [
{
$match: {
DateTime: {
$gte: lastDate.LastRunDateTime
}
}
},
{
$group: {
_id: "$PostId",
likesCount : { $sum: "$Like" },
commentsCount : { $sum: "$Comment"}
}
},
{
$merge: {
into: "PostAggregate",
whenMatched: "replace"
}
}
] ).toArray().then(result => {
console.log(`Successfully ran post-aggregate pipeline`)
// update datetime for next run
context.functions.execute("updatePostAggregateHistory", currDate)
return result
}).catch(err => console.error(`Failed to run post-aggregate pipeline: ${err}`))
};