golang mongo-driver Aggregate

分组计算

// ListGroupByUser group by user
func (repo PostReadRepository) ListGroupByUser(postUID string) (list []*model.PostRead, err error) {
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    pipeline := []bson.M{bson.M{"$group": bson.M{"_id": bson.M{"postuid": "$postuid", "createdby": "$createdby"},
        "createdon": bson.M{"$max": "$createdon.t"}, "uid": bson.M{"$max": "$_id"}, "readtime": bson.M{"$sum": "$readtime"}}}}
    opts := options.Aggregate()
    cur, err := dbPostRead.Aggregate(ctx, pipeline, opts)
    defer cur.Close(ctx)

    for cur.Next(ctx) {
        var doc map[string]interface{}
        cur.Decode(&doc)
        createdOn, _ := time.ParseInLocation("2006-01-02T15:04:05", doc["createdon"].(string), time.Local)
        read := &model.PostRead{
            UID:       doc["uid"].(string),
            PostUID:   doc["_id"].(map[string]interface{})["postuid"].(string),
            ReadTime:  doc["readtime"].(int64),
            CreatedOn: mask.Timestamp{Time: createdOn},
            CreatedBy: doc["_id"].(map[string]interface{})["createdby"].(string),
        }
        read.User = proxy.GetUserInfo(read.CreatedBy)

        list = append(list, read)
    }
    return
}

你可能感兴趣的:(golang mongo-driver Aggregate)