If I have a user and post collection
{\"_id\": 1, \"name\": \"User 1\"}
{\"_id\": 2, \"name\": \"User 2\"}
{\"_id\": 1, \"title\":
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.