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

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 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组