限制在组中推送返回的项目

Limit items returned in push with group

我需要按发件人分组 (fleche) 并从每个发件人那里获取最后一条消息。我通过 $push$group 成功实现了这个想法 但它 return 每个 'fleche' (发件人)的所有消息。与消息日期相同的 pb,最后一个元素应该是 enought 。 mongo 2.6.6 with aggregation framework 有可能吗?
预期结果、我的实际查询的实际结果、实际查询和消息收集示例附在下面:
预期结果:

"result" : [ 
    {
        "_id" : 1,
        "date" : [ 
            1421948851800
        ],
        "mess" : [ 
            "dernier mess ffsdfsdfsd 2" 
        ]
    }, 
    {
        "_id" : 3,
        "date" : [ 
            1421948859593
        ],
        "mess" : [ 
            "dernier mess ffsdfsdfsd 2"

        ]
    }

实际查询的实际结果:

"result" : [ 
    {
        "_id" : 1,
        "date" : [ 
            1421948851800, 
            1421947200606, 
            1421947163929, 
            1421947153646, 
            1421946853567
        ],
        "mess" : [ 
            "dernier mess ffsdfsdfsd 2", 
            "fssdfencore didon ! fds 2", 
            "fsd fds fds 2", 
            "safdsfdsfs sdf fie2", 
            "salut la companie"
        ]
    }, 
    {
        "_id" : 3,
        "date" : [ 
            1421948859593, 
            1421947176679, 
            1421947098168
        ],
        "mess" : [ 
            "dernier mess ffsdfsdfsd 2", 
            "fssdfsdffsd ss fds 2", 
            "salut la companie"
        ]
    }

实际查询:

db.messages.aggregate([

    {$match :{cible :2 , lu:0} } ,
    { $sort : { date : -1 } },
    { $group : {_id : "$fleche", date : { $push : "$date" } , mess :{$push: "$mess" }   } } ,
    {$limit:20}

])

消息收集示例:

{
    "_id" : ObjectId("54c12fe5a48da55ee08c7804"),
    "fleche" : 1,
    "cible" : 2,
    "date" : 1421946853567,
    "mess" : "salut la companie",
    "lu" : 0
}
{
    "_id" : ObjectId("54c130daa48da55ee08c7805"),
    "fleche" : 3,
    "cible" : 2,
    "date" : 1421947098168,
    "mess" : "salut la companie",
    "lu" : 0
}
{
    "_id" : ObjectId("54c13111a48da55ee08c7807"),
    "fleche" : 1,
    "cible" : 2,
    "date" : 1421947153646,
    "mess" : "safdsfdsfs sdf fie2",
    "lu" : 0
}
{
    "_id" : ObjectId("54c1311ba48da55ee08c7808"),
    "fleche" : 1,
    "cible" : 2,
    "date" : 1421947163929,
    "mess" : "fsd fds fds 2",
    "lu" : 0
}
{
    "_id" : ObjectId("54c13128a48da55ee08c7809"),
    "fleche" : 3,
    "cible" : 2,
    "date" : 1421947176679,
    "mess" : "fssdfsdffsd ss fds 2",
    "lu" : 0
}

您可以使用 $first or $last

db.messages.aggregate([

    {$match :{cible :2 , lu:0} } ,
    { $sort : { date : -1 } },
    { $group : {_id : "$fleche", date : { $first : "$date" } , mess :{$first: "$mess" }   } } ,
    {$limit:20}

])

输出将是:

{
    "result" : [ 
        {
            "_id" : 1,
            "date" : 1421947163929,
            "mess" : "fsd fds fds 2"
        }, 
        {
            "_id" : 3,
            "date" : 1421947176679,
            "mess" : "fssdfsdffsd ss fds 2"
        }
    ],
    "ok" : 1
}