how to sort the comments in joins
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
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