限制推送组中返回的项目

时间:2015-01-22 18:41:29

标签: mongodb mongodb-query aggregation-framework

我需要按发件人分组(fleche)并从每个消息中获取最后一条消息。我通过 $ push $ group 成功实现了这个想法,但它返回了每个'fleche'(发件人)的所有消息。与消息日期相同的pb,应该是最后一个元素。是否可以在mongo 2.6.6 上使用聚合框架
预期结果,实际查询,实际查询和消息收集样本的实际结果如下:
预期结果:

"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
}

1 个答案:

答案 0 :(得分:4)

您可以使用$first$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
}