mongodb apply sort to lookup results

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

提交回复
热议问题