【问题标题】:How to do mongo aggregation如何做mongo聚合
【发布时间】:2021-05-26 23:44:09
【问题描述】:

我正在尝试编写一个查询,该查询给出创建日期等于 365 的文档。 我在 mongo 指南针中尝试了聚合,但不知道如何在 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 ',' before newline in composite literal syntax

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})

【问题讨论】:

    标签: mongodb go aggregation


    【解决方案1】:

    在 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)
    

    【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2018-07-15
    • 2017-08-24
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多