如何在Mongo Group之后获取额外的数据

时间:2016-02-05 12:19:45

标签: node.js mongodb mongoose

考虑mongoDb中的以下数据,我在那里存储用户活动。其中timestamp是创建记录的时间。

我想要每个用户最近的活动。

{ user: "A", activity : "act1" , date: timestamp}
{ user: "B", activity : "act3" , date: timestamp}
{ user: "C", activity : "act2" , date: timestamp}
{ user: "A", activity : "act2" , date: timestamp}
{ user: "B", activity : "act3" , date: timestamp}
{ user: "C", activity : "act1" , date: timestamp}

使用

分组
db.aggregate({
  [  
     $group: {
       _id: "$user",
       latest_activity_time: {$max: "$date"},
     }
  }])

仅给我最近的活动时间,我无法获得最近的活动。

1 个答案:

答案 0 :(得分:1)

首先使用 $sort 管道运算符在管道中订购现有文档,然后使用 $first {{3} $last 步骤中的累加器运算符,具体取决于之前的排序方向:

var pipeline = [
    { "$sort": { "date": -1 } }, // or order by date ascending { "$sort": { "date": 1 } }
    {
        "$group": {
            "_id": "$user",
            "latest_activity": { "$first": "$activity" }, // if ordered by date ascending "latest_activity": { "$last": "$activity" }
            "latest_activity_time": { "$first": "$date" } // if ordered by date ascending "latest_activity_time": { "$last": "$date" }
        }
    }
];

Model.aggregate(pipeline)
     .exec(function (err, result){
         console.log(JSON.stringify(result, null, 4));
     });