mongodb apply sort to lookup results

前端 未结 3 1223
一生所求
一生所求 2020-12-10 14:44

If I have a user and post collection

{\"_id\": 1, \"name\": \"User 1\"}
{\"_id\": 2, \"name\": \"User 2\"}

{\"_id\": 1, \"title\":         


        
3条回答
  •  [愿得一人]
    2020-12-10 15:05

    I solved the duplicates using $group and $first

    db.getCollection('user').aggregate([
        {$lookup: {from: "post", localField: "_id", foreignField: "userId", as: "post"}},
        {$unwind: { path: "$post", preserveNullAndEmptyArrays: true }},
        {$sort: {"post.createdAt": -1}},
        {$group: {"_id": "$_id", "name": {$first: "$name"}, "post": {$first: "$post"}},
        {$project: {"_id": 1, "name": 1, post": 1}}
    ])
    

    Feel free to post your answer

提交回复
热议问题