登录
首页 >  Golang >  Go问答

MongoDB聚合操作的实施

来源:stackoverflow

时间:2024-02-27 17:45:23 370浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《MongoDB聚合操作的实施》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我正在尝试编写一个查询,给出creationdate等于365的文档。 我尝试了 mongo compass 中的聚合,但不知道如何在 go 中翻译它。以下是我在 mongo compass 中尝试过的内容

[{$project: {filename:1,filetype:1,filedata:1,subtractdate: {$eq:[{$trunc:{$divide:[{$subtract:[newdate(),"$creationdate"]},1000*60*60*24]}},365]}}}]

由此,我创建了一个视图并将过滤器应用为 - {subtractdate:true}

下面是我的 golang 代码,请帮助我了解我做错了什么,因为出现错误 - missing ',' 在复合文字语法中的换行符 之前

matchStage := bson.D{{"$match", bson.D{{}}}}
groupStage := bson.D{{"$project": bson.D{{"fileName": 1,"fileType": 1,"fileData": 1,"subtractDate":bson.D{{"$trunc": bson.D{{"$divide": []bson.D{{"$subtract": []time.Time{time.Date(),"$creationDate"}},1000 * 60 * 60 * 24}}}}}}}}}
myCollection  := client.Database("dbname").Collection("collectionName")
filterCursor2,err = myCollection.Aggregate(ctx,mongo.Pipeline{matchStage,groupStage})

解决方案


在 mongo 聚合中可以使用 golang 类型

agg := []map[string]interface{}{
        map[string]interface{}{
            "$project": map[string]interface{}{
                "filename":1,
                "filetype":1,
                "filedata":1,
                "subtractdate": map[string]interface{}{
                    "$trunc": map[string]interface{}{
                        "$divide": []interface{}{
                            map[string]interface{}{
                                "$subtract": []interface{}{time.now(), "$creationdate"},
                            },
                            1000*60*60*24,
                        },
                    },
                },
            },
        },
        map[string]interface{}{
            "$match": map[string]interface{}{
                "subtractdate": 365,
            },
        },
    }

只需将聚合选项放入集合的聚合方法

cur, err := db.collection("collectionname").aggregate(context.todo(), agg)
if err != nil {
    log.println(err.error())
}

然后获取结果

var result []map[string]interface{}
for cur.Next(context.TODO()) {
    var elem map[string]interface{}
    err := cur.Decode(&elem)
    if err != nil {
        log.Println(err.Error())
    } else {
        result = append(result, elem)
    }
}
if err := cur.Err(); err != nil {
    log.Println(err.Error())
}

log.Println(result)

理论要掌握,实操不能落!以上关于《MongoDB聚合操作的实施》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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