mongoose: how to sort with aggregate search

GI HYUN NAM

I have this aggregate search function

filter = { 'games.game_info.game_time': -1 };
.aggregate([
                {
                    $match: {}
                },
                {
                    $project: {
                        games: 1,
                        game_number: {
                            $size: '$games'
                        }
                    }
                },
                {
                    $facet: {
                        paginatedResult: [ { $sort: filter } ]
                    }
                }
            ])

games has this array.

  games:  [
      {
        game_id: '1',
        game_type: 'GTA5',
        game_info: {
          game_time: '2021-01-17 02:30:00.000Z',
          sports_code: '2'
        },
      },
      {
        game_id: '2',
        game_type: 'GTA5',
        game_info: {
          game_time: '2021-01-17 08:45:00.000Z',
          sports_code: '2'
        },
      }
    ]

I am trying to sort the list by the time. However, I am stuck on this. Tried various methods. How can I make filter works with +1 or -1 in order to sort the list by closest or latest time?

bkmalan

You can sort it like this.You can also get total number of records using $count.

Games.aggregate([
        {
            $facet: {
                data: [
                    { $match: { game_type: 'GTA5' } },
                    { $sort: { 'game_info.game_time': -1 } }
                ],
                total_count: [
                     { $count: 'count' }
                ]
            }
        }
    ]);

Hope it helped... :)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related