Sort comments in new lookup

how to sort the comments in joins

Hi @Chandrashekhara_26813,

You can use $sort stage in pipeline in $lookup.

// Pipeline
[


    // Stage 1
    {
        $unwind: {
            path : "$meta"
        }
    },

    // Stage 2
    {
        $sort: {
          'meta.views':-1
        }
    },

]

Kanika

I have used this approach:

[{
      $match: {
        _id: ObjectId(id),
      },
    },
    {
      '$lookup': {
        'from': 'comments',
        'let': {
          'id': '$_id'
        },
        'pipeline': [{
            '$match': {
              '$expr': {
                '$eq': [
                  '$movie_id', '$$id'
                ]
              }
            }
          },
          {
            $sort: {
              "date": -1
            }
          }
        ],
        'as': 'comments'
      },
    }
  ]
1 Like

Hi @tebaiot,

This is absolutely the right way!
Let us know if you have any other issues.

Kanika

1 Like

Hi. This works, but i don’t understand why do we need to match twice?

The second $match is under new $lookup operator to match $id from movies with $movie_id from comments collection.

Kanika