登录
首页 >  Golang >  Go问答

使用golang进行mongodb的聚合查询

来源:stackoverflow

时间:2024-02-09 20:00:24 108浏览 收藏

从现在开始,努力学习吧!本文《使用golang进行mongodb的聚合查询》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我能够运行以下 mongodb 聚合查询并在 mongo db 中获得所需的结果。我希望在 golang 中运行聚合查询时得到相同的结果。但是,我按预期获取了所有字段值(即持续时间、totaltime),但查询中的两个字段(即 displayname、msid)显示空字符串值。它应该包含非空字符串值,如 mongo db 查询结果中所示。我在 golang 查询中缺少什么?

mongodb聚合查询-

db.getcollection("db").aggregate(
    [
        { 
            "$match" : { 
                "attendancedate" : "07/26/2022"
            }
        }, 
        { 
            "$unwind" : "$history"
        }, 
        { 
            "$set" : { 
                "timediff" : { 
                    "$divide" : [
                        { 
                            "$subtract" : [
                                "$history.endtime", 
                                "$history.starttime"
                            ]
                        }, 
                        60000.0
                    ]
                }
            }
        }, 
        { 
            "$group" : { 
                "_id" : { 
                    "status" : "$history.status", 
                    "displayname" : "$displayname", 
                    "msid" : "$msid"
                }, 
                "duration" : { 
                    "$sum" : "$timediff"
                }
            }
        }, 
        { 
            "$group" : { 
                "_id" : { 
                    "displayname" : "$_id.displayname", 
                    "msid" : "$_id.msid"
                }, 
                "durations" : { 
                    "$push" : { 
                        "key" : "$_id.status", 
                        "value" : "$duration"
                    }
                }
            }
        }, 
        { 
            "$addfields" : { 
                "displayname" : "$_id.displayname", 
                "msid" : "$_id.msid", 
                "totaltime" : { 
                    "$sum" : "$durations.value"
                }
            }
        }
    ]
);

上面 mongo 中查询的结果 -

{ 
    "_id" : {
        "displayname" : "john, doe", 
        "msid" : "abcd"
    }, 
    "durations" : [
        {
            "key" : "other", 
            "value" : numberint(0)
        }, 
        {
            "key" : "break", 
            "value" : 1.9216166666666668
        }, 
        {
            "key" : "lunch", 
            "value" : 0.9956666666666667
        }, 
        {
            "key" : "in", 
            "value" : 9.3131
        }, 
        {
            "key" : "training", 
            "value" : 0.9886666666666667
        }
    ], 
    "displayname" : "john, doe", 
    "msid" : "abcd", 
    "totaltime" : 13.219050000000001
}

golang 代码 -

type AttendanceAggregate struct {
    DisplayName string                    `json:"displayName" bson:"displayName"`
    ID          string                    `json:"msId" bson:"msId"`
    TotalTime   float64                   `json:"totalTime" bson:"totalTime"`
    Duration    []AttendanceAggregateItem `json:"durations" bson:"durations"`
}

type AttendanceAggregateItem struct {
    Key   string  `json:"key,omitempty" bson:"key,omitempty"`
    Value float64 `json:"value,omitempty" bson:"value,omitempty"`
}


 func (r *repo) Find() ([]domain.AttendanceAggregate, error) {

    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    var attendances []domain.AttendanceAggregate

    pipeline := []bson.M{
        {
            "$match": bson.M{
                "attendanceDate": "07/26/2022",
            },
        },
        {
            "$unwind": "$history",
        },
        {
            "$set": bson.M{
                "timeDiff": bson.M{
                    "$subtract": bson.A{
                        "$history.endTime",
                        "$history.startTime",
                    },
                },
            },
        },
        {
            "$set": bson.M{
                "timeDiff": bson.M{
                    "$divide": bson.A{
                        "$timeDiff",
                        60000.0,
                    },
                },
            },
        },
        {
            "$group": bson.M{
                "_id": bson.M{
                    "status":      "$history.status",
                    "displayName": "$displayName",
                    "msId":        "$msId",
                },
                "duration": bson.M{
                    "$sum": "$timeDiff",
                },
            },
        },
        {
            "$group": bson.M{
                "_id": bson.M{
                    "displayName": "$displayName",
                    "msId":        "$msId",
                },
                "durations": bson.M{
                    "$push": bson.M{
                        "key":   "$_id.status",
                        "value": "$duration",
                    },
                },
            },
        },
        {
            "$addFields": bson.M{
                "displayName": "$_id.displayName",
                "msId":        "$_id.msId",
                "totalTime": bson.M{
                    "$sum": "$durations.value",
                },
            },
        },
    }

    cur, err := r.Db.Collection("db").Aggregate(ctx, pipeline)
    defer cur.Close(ctx)
    if err != nil {

        return attendances, err
    }

    for cur.Next(ctx) {
        var attendance domain.AttendanceAggregate

        err := cur.Decode(&attendance)
        if err != nil {
            return attendances, err
        }
     
        attendances = append(attendances, attendance)
    }

    if err = cur.Err(); err != nil {
        return attendances, err
    }

    return attendances, nil
}

golang查询结果截图- golang查询结果截图


正确答案


go 中的最后一个 $group 阶段缺少 displaynamemsid 字段中的 _id 前缀:

而不是:

{
        "$group": bson.m{
            "_id": bson.m{
                "displayname": "$displayname",
                "msid":        "$msid",
            },
            "durations": bson.m{
                "$push": bson.m{
                    "key":   "$_id.status",
                    "value": "$duration",
                },
            },
        },
    },

用途:

{
        "$group": bson.M{
            "_id": bson.M{
                "displayName": "$_id.displayName",
                "msId":        "$_id.msId",
            },
            "durations": bson.M{
                "$push": bson.M{
                    "key":   "$_id.status",
                    "value": "$duration",
                },
            },
        },
    },

本篇关于《使用golang进行mongodb的聚合查询》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>