Tom3652
Tom3652

Reputation: 2967

Aggregate in MongoDB Atlas trigger not working

I have this aggregation pipeline i wrote in NodeJS in my Atlas Trigger :

  const pipeline = [
    {$match: {"score": {$gt: 0}, "update": true}},
    {$setWindowFields: {sortBy: {"score": -1}, output: {"rank": {$denseRank: {}}}}},
    {$merge: {into: "ranking"}}
  ];
  
  await ranking_col.aggregate(pipeline);

I have written this pipeline in python first for testing and it's working just fine :

self.db.ranking.aggregate([
            {
                "$match": {
                    "score": {"$gt": 0},
                    "update": True
                }
            },
            {
                '$setWindowFields': {
                    'sortBy': {'score': -1},
                    'output': {
                        'rank': {
                            '$denseRank': {

                            }
                        }
                    }
                }
            },
            {
                "$merge": {
                    "into": "ranking"
                }
            }
        ])

I have no errors from the Trigger logs but it seems that the pipeline is simply not executed as it should modify the ranking as it's done in python.

Can you please tell me what am i doing wrong here ?

EDIT : The database scheme (as simple as the query is)

See below one document of ranking_col :

{
  "_id": "7dqe1kcA7R1YGjdwHsAkV83",
  "score": 294,
  "update": false,
  "rank": 0,
}

The aggregation is simply here to calculate the rank attribute according to the score.

Upvotes: 2

Views: 1068

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

Ok so the issue relies in the Mongo driver the function uses on atlas and your understanding of it.

aggregate returns an AggregateCursor, which means until you trigger it no command is actually getting executed, this means your trigger is actually running fine, but because no one is using the cursor it just exits the function without doing anyways.

A super simple solution would be to just add .toArray(), this will convert the cursor to an array of documents. essentially triggering the functionality:

await ranking_col.aggregate(pipeline).toArray();

Upvotes: 4

Related Questions