mongodb不同于groupby多个键

时间:2015-06-20 19:02:57

标签: mongodb aggregation-framework

我试图查询mongoDB以获取数据聚合(group,match,last)。这是我的文件:

{
    "_id" : 1,
    "from" : "a",
    "to" : "b",
    "message" : "a to b",
    "createdAt" : ISODate("2015-06-06T16:42:32.789Z"),
    "updatedAt" : ISODate("2015-06-06T16:42:32.789Z")
}
{
    "_id" : 4,
    "from" : "a",
    "to" : "c",
    "message" : "a to c2",
    "createdAt" : ISODate("2015-06-06T16:45:32.789Z"),
    "updatedAt" : ISODate("2015-06-06T16:45:32.789Z")
}
{
    "_id" : 5,
    "from" : "b",
    "to" : "c",
    "message" : "b to c2",
    "createdAt" : ISODate("2015-06-06T16:46:32.789Z"),
    "updatedAt" : ISODate("2015-06-06T16:46:32.789Z")
}

现在,我想使用最近的组合获取一个文档。例如:

db.collection.aggregate({$match:{$or:[{"from":"552e5d7b62c6a4c67093be5d"},{"to":"552e5d7b62c6a4c67093be5d"}]}})

我试过这个:

{{1}}

感谢您对代码的任何帮助。

1 个答案:

答案 0 :(得分:1)

使用以下聚合管道获得所需的结果:

db.collection.aggregate([
    {
        "$sort": {
            "updatedAt": -1
        }
    },
    {
        "$group": {
            "_id": {
                "to": "$to",
                "from": "$from"                
            },
            "id": { "$first": "$_id" },
            "message": { "$first": "$message" },
            "createdAt": { "$first": "$createdAt" },
            "updatedAt": { "$first": "$updatedAt" }
        }
    },
    {
        "$project": {
            "_id" : 0,
            "id": 1,
            "from" : "$_id.from",
            "to": "$_id.to",
            "message": 1,
            "createdAt": 1,
            "updatedAt": 1
        }
    }
])