mongodb apply sort to lookup results

前端 未结 3 1213
一生所求
一生所求 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:04

    here is a way you can use

    db.getCollection('post').aggregate([
    { $limit: 10 },
    
    {$sort: {"createdAt": -1}},
    
    {$lookup: {from: "user", localField: "userId", foreignField: "_id", as: "user"}},
    ])
    

    you should query post which sorted by date and join with user. so if you want to provide a limit for posts then you can.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-10 15:25

    You can solve this in a single aggregation step with the new $lookup syntax

    db.getCollection('users').aggregate([{
        '$lookup': {
          'from': 'posts',
          'let': {
            'userId': '$_id'
          },
          'pipeline': [{
              '$match': { '$expr': { '$eq': ['$userId', '$$userId'] } }
            }, {
              '$sort': {  'createdAt': -1 }
            }, {
              '$limit': 10
            },
          ],
          'as': 'posts'
        }
      }
    ])
    

    Note: untested code, but the principle should be clear.

    0 讨论(0)
提交回复
热议问题