I have a MongoDB collection like this:
{ "_id" : ObjectId("5a017ee061313781045889ea"), "device_id" : "1232213", "value" : "23233", "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
{ "_id" : ObjectId("5a017f7b61313781045889eb"), "device_id" : "1111", "value" : "23233", "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : ObjectId("5a017fdd61313781045889ec"), "device_id" : "12222", "value" : "23233", "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : ObjectId("5a017ff561313781045889ed"), "device_id" : "1232213", "value" : "23233", "pubtime" : ISODate("2017-11-07T09:42:13.658Z") }
I want to distinct it by "device_id"
AND sort it by "pubtime"
.
I know that Golang could use pipe to do it. But I don't know how to do it. What I tried:
o1 := bson.M{"_id": bson.M{"device_id": "$device_id"}}
o2 := bson.M{"pubtime": bson.M{"$last": "$pubtime"}}
o3 := bson.M{"$group": []bson.M{o1, o2}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
_ = pipe.All(&result)
fmt.Println(result)
The result is empty.
It is ok in MongoDB:
db.collections.aggregate({"$group":
{"_id":{"device_id":"$device_id"},
"pubtime":{"$last": "$pubtime"} ,
"value":{"$last": "$value"} ,
}});