dpd2349 2018-03-11 17:35
浏览 1005
已采纳

Golang MGO Group按多个参数分组并按日期时间获取最后一个

I am using Golang and the MGO library

I have some test records where I want to GROUP BY the serial number, stage, stage order and grab the last record by the datetime field. Most instances there is 1 record that per serial/stage/stage order but there can also be instances where there are multiple tests and I would like to grab the last test completed, not all of them for that combination.

So, in short, there are records in my table that will have the same serial, stage, and stage order but different timestamps, I want to grab the last or only record for the entire data set so that I have a single record for every (serial, stage, stage order) combination and if there were duplicate tests I always grab the last record in that group.

enter image description here

With the above example I ONLY want to get the 2nd record back for that serial.

My Code: I was trying to create a pipeline but can't seem to get it setup correctly:

pipeline := []bson.M{
    bson.M{
        "$match": bson.M{"workorder": i},
    },
    bson.M{
        "$group": bson.M{
            "_id": "id",
            "serial": bson.M{"$match": "$serial"},
            "stage": bson.M{"$match": "$stage"},
            "order": bson.M{"$match": "$order"},
            "date": bson.M{"$last": "$date_timestamp"},
            },
    },
}
  • 写回答

1条回答 默认 最新

  • dongyashun2559 2018-03-11 19:47
    关注

    Try below aggregation.

    Add $sort before $group.

    sort := bson.M{
        "$sort": bson.M{
        "date_timestamp": -1
      }
    }
    
    group := bson.M{
      {"$group": bson.M{
         "_id": "$serial", 
         "stage": bson.M{"$last":"$stage"}, 
         "order": bson.M{"$last":"$order"}, 
         "datetime": bson:M{"$last":"$date_timestamp"}
      }}
    }
    
    pipeline:= []bson.M{sort, group}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝