1

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?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
Vladimir
  • 1,751
  • 6
  • 30
  • 52
  • 2
    did you try using `$slice` on in the next part of aggregation pipeline to limit them. see https://docs.mongodb.com/manual/reference/operator/aggregation/slice/ – raj Dec 01 '16 at 13:51
  • 1
    Possible duplicate of [Mongodb aggregation pipeline how to limit a group push](http://stackoverflow.com/questions/24594049/mongodb-aggregation-pipeline-how-to-limit-a-group-push) – styvane Dec 01 '16 at 15:13

1 Answers1

1

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]}}}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471