Vladimir Vladimir - 9 days ago 5
Node.js Question

Limit on $push aggregation

I have group like this:

{
"$group": {
"_id": "$conversationId"
"conversation": {
"$push": {"from": {
"firstName": "$fromObj.firstName",
"lastName": "$fromObj.lastName",
"title": "$fromObj.title",
"picture": "$fromObj.picture"

}
, "to": {
"firstName": "$toObj.firstName",
"lastName": "$toObj.lastName",
"title": "$toObj.title",
"picture": "$toObj.picture"
}
, "content": "$content",
"_id": "$_id",
"conversationId": "$conversationId",
"unreaded": "$unreaded"
}}

}

}


Inside
$push
part I need to push just last 5 items how can I do that? It would be ideal if is it possible to add $limit directly to $push any solution for this?

Answer

You can do this by adding a $project stage to your pipeline after the $group that uses $slice to take just the last 5 elements from the accumulated conversation array of each doc:

{$project: {conversation: {$slice: ['$conversation', -5]}}}