1

I have used $ lookup to make left join but I am not able to sort the result by created_at field in posts

My query

pipeline =  [{$match: { "_id" :  mongoose.Types.ObjectId(req.body.celebrity_id)}},
               {$lookup : { from : "posts" , localField : "_id" ,foreignField : "celebrity_id", as : "posts"}},
               ]`

User.aggregate( pipeline )
.exec(function(err , user){

    console.log(user)
    if(err){

      res.json({'success' : false , msg : 'Something went wrong please try again'});
    }else{

      res.json({'success' : true  , msg : 'success' , 'data' : user });
    }
})

Now I want to sort the posts array in descending order by created_at field

Irfan Khan
  • 395
  • 4
  • 14
  • You need to `$unwind` the array then `$sort` and `$group` back again. It's the same process as sorting any array in the aggregation pipeline. As yet there is no way to sort an array without using `$unwind`. – Neil Lunn Sep 05 '17 at 13:01
  • ok thanks I think that is the only way I have to do it – Irfan Khan Sep 05 '17 at 13:06
  • It is. We can `$map` or `$filter` and even `$reduce` an array inline ( also `$sum` `$avg` `$min` `$max` all reduce like operations ) and even `$reverseArray`. The day the same sort of operation becomes available for "sort" I will personally jump for joy. A much needed feature. – Neil Lunn Sep 05 '17 at 13:10
  • Yeah thats right – Irfan Khan Sep 05 '17 at 13:16

0 Answers0